2012-05-28 127 views
0

的点击警告我创建了一个按钮:创建一个按钮

var removeButton = document.createElement('button'); 
    $(removeButton).attr('class', 'removeProduct'); 
    $(removeButton).append(document.createTextNode('X')); 
    $(removeButton).data('divId', 'productLine' + numProductsInCart); 

这个工作,会出现按钮。

但是,当我尝试在被点击的按钮上产生警报时,它不起作用。我点击按钮,它什么都不做。

这里是我有这么远:

$('.removeProduct').click(function() { 
    alert("Hey"); 
}); 
+0

事件是否绑定到元素? –

+0

在将事件处理程序绑定到它之前,您必须将元素添加到DOM树中,或者使用'$(removeButton).click(...)'而不是选择器。另外,由于jQuery显着简化了DOM操作,因此使用它来创建元素。例如。'$('

回答

4

我假设你正在尝试之前,该事件处理程序绑定你添加按钮的DOM。如果是这样的话,你需要委派的事件处理程序越往上DOM树:

$("#someAncestorElement").on("click", ".removeProduct", function() { 
    alert("Hey"); 
}); 

这工作,因为DOM事件往往会冒泡从其所源自该元素的树。您可以捕捉任何祖先元素的事件。 on method将检查事件目标是否匹配选择器,如果是,则运行事件处理程序。请注意,如果您使用的是1.7以下版本的jQuery,则需要使用delegate而不是on

$(removeButton).on("click", function() { 
    alert("Hey"); 
}); 
0

试试这个

$(document).ready(function(){ 
    $('.removeProduct').live("click", function() { 
     alert("Hey"); 
    }); 
}); 
+2

不要使用'live',它已被弃用。除非你被困在一个古老的jQuery''on''上,否则''delegate'是首选。 –

+0

谢谢詹姆斯我会详细检查它。 –

0

你可能会试图选择按钮($('.removeProduct'))已将其添加到文档之前(我没有在您的示例代码中看到将它添加到文档中的位置)。当您添加onclick处理程序时,您不能使用现有的removeButton引用吗?

0

请确保第一位代码已在第二位之前运行。否则,它没有更新该按钮的类别为removeProduct,并且没有任何可绑定的内容。

$(document).ready(function(){ 
    $('.removeProduct').click(function() { 
    alert("Hey"); 
    }); 
}); 
0

尝试on方法:

$('<button>X</button>').addClass('removeProduct').attr('data-Id', 'productLine' + numProductsInCart).appendTo('div'); 

$('.removeProduct').on('click', function() { 
    alert("Hey"); 
}); 

http://jsfiddle.net/9gJPL/1/

+1

不要使用'live',它已被弃用。除非你被困在一个古老的jQuery''on''上,否则''delegate'是首选。 –

+0

@James Allardice你说得对,'live'已经被弃用了。 – undefined

+0

您的更改无效(假定稍后将元素添加到DOM)。你需要传递一个选择器到'on'来让它委托事件处理器。 –

0

你是不是想追加屏幕上的按钮前添加单击处理程序:

或者,你所创建的元素之后,你可以绑定的事件处理程序?此代码的工作对我来说:

// Append the button 
​$("body").append(removeButton);​ 

// Now add the handler 
$('.removeProduct').on("click", function() { 
    alert("Hey"); 
}); 

也可以添加该按钮的处理程序,追加前:

$(removeButton).on("click", function() { 
    alert("Hey"); 
}); 

所以,现在,让我们来重构代码一点:

function clickHandler(e) { 
    alert("Hey"); 
} 

var removeButton = $("<button/>") 
        .html("X") 
        .addClass('removeProduct') 
        .data('divId', 'productLine' + numProductsInCart)      
        .on("click", clickHandler); 

​$("body").append(removeButton);​ 

希望能帮助到你!