[英]how bind event dynamically
如何将动态事件绑定到创建的元素中? 我将尝试使用此代码,但元素始终使用变量i(i = 8)的最后状态,范围是否存在问题?
console.log('add all children');
var myloc = window.location.href + "jquery";
var jquerySample = 8;
for (i = 1; i <= jquerySample; i++) {
var element=jQuery('<div/>', {
id: 'subitemElement' + i,
href: myloc + "/test_jQ_" + i,
class: 'subitem',
rel: 'external',
text: "test_jQ_" + i,
click: function(num) {
console.log("subitem jquery click");
window.location = myloc + "/test_jQ_" + num;
}(i)
});
element.appendTo('#itemJQUERY');
event.preventDefault();
}
我认为使用以下代码会更成功:
console.log('add all children');
var myloc = window.location.href + "jquery";
var jquerySample = 8;
for (i = 1; i <= jquerySample; i++) {
var element = $(document.createElement('div'))
.attr(
{
id: 'subitemElement' + i,
rel: 'external'
})
.data(
{
url: myloc + "/test_jQ_" + i,
})
.text('test_jQ_' + i)
.addClass('subitem')
.click(function(e)
{
window.location = $(this).data('url');
});
element.appendTo('#itemJQUERY');
}
div没有名为href的属性。 将其另存为数据。
在这里查看jsfiddle: 有效的小提琴
jQuery('#itemJQUERY').on('click','.subitem',function(){
window.location = $(this).data('url');
});
var myloc = window.location.href + "jquery";
var jquerySample = 8;
for (i = 1; i <= jquerySample; i++) {
var element=jQuery('<div/>', {
id: 'subitemElement' + i,
class: 'configureClass'
href: myloc + "/test_jQ_" + i,
class: 'subitem',
rel: 'external',
text: "test_jQ_" + i
});
element.appendTo('#itemJQUERY');
event.preventDefault();
}
//if Jquery - 1.7
$(".configureClass").live(click,function(){
window.location = myloc + $(this).text();
});
//if Jquery - > 1.9
$(".configureClass").on(click,function(){
window.location = myloc + $(this).text();
});
上面的代码将起作用! 不要在html中绑定任何JS事件。 将其分开。
编码愉快!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.