简体   繁体   English

jQuery live无法正常工作

[英]jQuery live not working

Why below code does not work: 为什么下面的代码不起作用:

$('button[name="publish"]', 'button[name="cancel"]').live('click', function(){
    alert('ddddd');
});

The html is generated dynamically which is basically facebook's Share dialog which has these two buttons: html是动态生成的,基本上是facebook的“共享”对话框,具有以下两个按钮:

<input type="button" name="publish" value="Share">
<input type="button" name="cancel" value="Cancel">
  • Reference to jQuery lib is fine and checked 对jQuery lib的引用很好并且已检查
  • Using ready handler 使用现成的处理程序

The page can be viewed here: 该页面可以在这里查看:

https://www.facebook.com/pages/Development-Application-Testing-Page/124719744278421?sk=app_126015774115928 https://www.facebook.com/pages/Development-Application-Testing-Page/124719744278421?sk=app_126015774115928

Your current selector is short for: 您当前的选择器是以下简称

$('button[name="cancel"]').find('button[name="publish"]')

That's not intended. 那不是故意的。 You're looking for: 您正在寻找:

$('button[name="publish"], button[name="cancel"]')

Because your selector is slightly wrong. 因为您的选择器有误。 Try this (note the fact that the entire selector expression is quoted): 试试这个(注意整个选择器表达式都被引用):

$('button[name="publish"], button[name="cancel"]').live('click', function(){
    alert('ddddd');
});

What you currently have is looking for the first part of the selector ( button[name="publish"] ) and using the second part of the selector as a context (in other words, it looks for elements that match button[name="publish"] and are descendants of elements matching button[name="cancel"] ). 当前,您正在寻找选择器的第一部分( button[name="publish"] ),并将选择器的第二部分用作上下文(换句话说,它将查找与button[name="publish"]并且是与button[name="cancel"] )匹配的元素的后代。

Also note that the live method is deprecated. 另请注意,不建议使用live方法。 If you're using jQuery 1.7+ use on . 如果你正在使用jQuery 1.7+使用on If you're using an older version then use delegate . 如果您使用的是旧版本,请使用delegate

It does not work because your are trying to select an "input" with a $('button...') 它不起作用,因为您尝试使用$('button ...')选择一个“输入”

try this 尝试这个

$('input[name="publish"] , input[name="cancel"]').live('click', function(){
    alert('ddddd');
});
$('input[name=publish] , input[name=cancel]').live('click', function(){
    alert('ddddd');
});

$('button[name="publish"], button[name="cancel"]').live('click', function(){
    alert('ddddd');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM