我有一个关于html类属性与javascript回调交互的问题。
假设我有一个表,每行都有一个这样的按钮:
<table border="0"> <?php foreach ($itemlist as $item => $value): ?> <tr> <td><?php echo $item;?></td> <td><button class="create-user">Test</button></td> </tr> <?php endforeach; ?> </table>请注意,该按钮的类属性为“create-user”。 现在我想为每个按钮添加相同的回调:
var btn = document.getElementsByClassName("create-user"); btn.click(function() { $("#dialog-form").dialog("open"); });我希望对话框形式会打开,但没有回应。 这是我第一次使用javascript处理class属性。
任何人都可以为我解释一下吗?
谢谢!
I have a question regarding the html class attribute interactive with the javascript call back.
Suppose I have a table and each row has a button like this:
<table border="0"> <?php foreach ($itemlist as $item => $value): ?> <tr> <td><?php echo $item;?></td> <td><button class="create-user">Test</button></td> </tr> <?php endforeach; ?> </table>Notice that the button has a class attribute as "create-user". Now I want to add the same callback for each button with this:
var btn = document.getElementsByClassName("create-user"); btn.click(function() { $("#dialog-form").dialog("open"); });I expected the dialog-form will open up but there is no response. This is my first time to deal with the class attribute along with javascript.
Can anyone shed some light for me?
Thanks!
最满意答案
getElementsByClassName返回类似数组的集合(技术上是一个nodeList )。 要向元素添加事件处理程序,您必须循环遍历它们:
var buttons = document.getElementsByClassName("create-user"); var count = buttons.length; while ( count-- ) { buttons[ count ].onclick = function () { $("#dialog-form").dialog("open"); }; }但是,由于您使用的是jQuery,因此您应该使用jQuery来选择元素,这不需要显式循环:
$(".create-user").click(function() { $("#dialog-form").dialog("open"); });PS为了提高性能,请记住缓存选择器:
var $dialog = $("#dialog-form"); $(".create-user").click(function() { $dialog.dialog("open"); });getElementsByClassName returns an array-like collection (technically a nodeList). To add an event handler to your elements, you'll have to loop through them:
var buttons = document.getElementsByClassName("create-user"); var count = buttons.length; while ( count-- ) { buttons[ count ].onclick = function () { $("#dialog-form").dialog("open"); }; }However, since you're using jQuery, you should use jQuery to select your elements, which won't require an explicit loop:
$(".create-user").click(function() { $("#dialog-form").dialog("open"); });P.S. For increased performance, remember to cache your selectors:
var $dialog = $("#dialog-form"); $(".create-user").click(function() { $dialog.dialog("open"); });更多推荐
发布评论