2013-04-16 39 views
0

我想弄清楚我用JQuery遇到的一個問題。當我在DOM中動態創建元素時,相關事件似乎不會觸發(例如:.hover)。不確定在動態創建元素時,是否必須以某種方式附加元素事件?提前致謝!回想動態創建的元素

HTML代碼:

<div id="dosages" style="display:none;"> 
     <h4>Choose a dosage</h4> 
     <ul id="dosagesUL" class="thumbnails"> 
     </ul> 
    </div> 

的Jquery/JavaScript的:

$("#medsSelect").change(function() { 

    var dosages = []; 
    var dosage; 
    var caption; 
    var image; 
    var html; 
    var idx; 

    $("#medsSelect option:selected").each(function() { 

     idx = $(this).attr("value"); 

     for (i = 0; i < medsArray[idx][1].length; i++) { 

      dosage = medsArray[idx][1][i]; 
      caption = medsArray[idx][2][i]; 
      image = medsArray[idx][3][i]; 

      html = "<li class=\"span2\">"; 
      html += "<div id=\"dosageIdx-\" + idx>"; 

      html += "<div class=\"thumbnail\">"; 
      html += "<img src=\"img/meds/" + image + ".png\">" 
      html += "</div>"; 

      html += "<div class=\"thumbnail-capbox\">"; 
      html += "<div class=\"med-label\">" + dosage + "</div>"; 
      html += "<div class=\"med-caption\">" + caption + "</div>"; 
      html += "</div>"; 

      html += "</div>"; 
      html += "</li>"; 

      dosages.push(html); 
     } 

    }); 

    $("#dosages").fadeOut(0); 
    $("#dosagesUL").empty(); 
    $("#dosagesUL").append(dosages.join('')); 
    $("#dosages").fadeIn(600); 

    }) 

    $('div[id*="dosageIdx-"]').hover(

     function() { 
      alert('in'); 
     }, 

     function() { 
      alert('out'); 
     } 
    ); 
+1

- [動態綁定事件創建元素](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) –

+0

- [在jQuery中,如何將事件附加到動態html元素](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) –

+0

- [添加jQuery點擊事件動態添加內容](http:///stackoverflow.com/questions/852450/adding-jquery-click-events-to-dynamically-added-content) –

回答

1

你應該委派的事件使用動態添加元素..

$(document).on('click','#elementID',function(){ 
     alert("clicked"); 
}) 

和懸停,因爲上()和懸停()不能使用,你可以使用mouseenter,而不是使用

$(document).on(
{ 
    mouseenter: function() 
    { 
    alert("mouseenter"); 
    }, 
    mouseleave: function() 
    { 
    alert("mouseleave"); 
    } 
}, '#elementID'); 

始終建議委託自己的活動,比document最接近的靜態父元素......而你的情況是#dosagesUL(我認爲)...是使用類,如果您有多個ID總是破越好..

$('#dosagesUL').on(
    { 
    ..... 
2

使用on()

$('body').on('mouseover', 'div[id*="dosageIdx-"]', function() { 
     alert('in'); 
    } 
); 
$('body').on('mouseout', 'div[id*="dosageIdx-"]', function() { 
     alert('out'); 
    } 
); 

不過,我建議你給這些div一個共同的類名,並用其作爲代替第二個選擇器。

改變這一行:(此行是無效的JS語法,如果你真的想打印變量idx的方式)

html += "<div id=\"dosageIdx-\" + idx>"; 

到:

html += "<div id=\"dosageIdx-" + idx + "\" class=\"specialHoverDiv\" \">"; 

,現在你可以做這而不是一個複雜的選擇器:

$('body').on('mouseover', '.specialHoverDiv', function() { 
+0

'+ 1'來提示課程使用情況。 – ahren

+0

的例子還有輕微的JS語法問題需要... + idx +「\」class = ...,感謝這個例子,工作就像一個魅力:) – Telegard