我正在尝试解决我在使用 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');
}
);