Search code examples
jquerydelegateslive

Can I dynamically delegate the variable id and delegate many variable "id" toggether with a function by jQuery?


var left=10;
var right=50;
$("#leftori").attr("id",left);
$("#rightori").attr("id",right);//change the id

$(document).delegate('div[id^='+left+']', 'mouseenter',function() {
  alert("left ok!");
  var newleft=left+1;
  $("#"+left).attr("id","newleft"};//change the id
  left=newleft;
 }
$(document).delegate('div[id^='+right+']', 'mouseenter',function() {
  alert("right ok!");
  var newright=right+1;
  $("#"+right).attr("id","newright");
  right=right+1;
}

<body>
<div id="leftori" class="div01"></div>
<div id="rightori" class="div01"></div>
</body>

The Questions are:

  1. How can I delegate the dynamical "id" on the new div which changed the id attribute on the second mouseenter event?
  2. I want to combine the selector with the id^=left or id^=right in the same delegate function . Can any method to make it? For example:

    $(document).delegate('div[id^='+left+']' || 'div[id^='+right+']' , 'mouseenter',function() {...}

But it cannot work well...How can I fix it or not have other method but to write in two delegate functions?


Solution

  • I would suggest that you don't change the ID of any DOM element - there are far better ways to keep "data" on a DOM element ....

    How about something like this :

    HTML :

    <div id="container">
       <div id="leftori" class="left"></div>
       <div id="rightori" class="right"></div>
    </div>
    

    JavaScript :

    var left=10;
    var right=50;
    // store the data
    $("#leftori").data("num",left);
    $("#rightori").data("num",right);
    
    $('#container').on('mouseenter','div',function() { 
        // update the data on mouseenter
        if ($(this).hasClass('left')){
            console.log('left');
            left++;
            $(this).data('num',left);
            console.log(left); 
            // or console.log($(this).data('num')); to access the new number
        } else if($(this).hasClass('right')) {
            console.log('right');
            right++;
            $(this).data('num',right);
            console.log(right);
            // or console.log($(this).data('num')); to access the new number
        }
    });
    

    Incase you are not aware - the console.log command logs the output to the browsers javascript console of a debugger (firebug).

    docs

    • on() -> replacement for delegate in jQuery 1.7
    • data() -> storing info on DOM elements
    • hasClass() -> check if the DOM element has a specific class

    Working example : http://jsfiddle.net/8RhbB/1/