jquery:单击以开头的每个 id 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6985136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: click for every id-element starting with
提问by michbeck
i try to find all id's starting with the string "matchItem_" and define a click-event for each. onclick i want wo execute a script with an url param and change the image in this id-element. unfortunatly my syntax isn't right, i also tried with .each.function but i didn't get it.
我尝试找到所有以字符串“matchItem_”开头的 ID,并为每个 ID 定义一个点击事件。onclick 我希望我们执行一个带有 url 参数的脚本并更改此 id 元素中的图像。不幸的是我的语法不正确,我也尝试过 .each.function 但我没有得到它。
please see my code:
请看我的代码:
$('[id^="matchItem_"]').each {
$(this).click(){
//...execute my script.php?urlparam=xx....;
$(this).find('img').attr('src','/admin/images/ok.png');
}
}
appreciate for somebody's help
感谢某人的帮助
thx in advance, michbeck
提前谢谢,米贝克
回答by Mrchief
You don't need the each
:
你不需要each
:
$('[id^="matchItem_"]').click(function() {
// do something
$(this).find('img').attr('src','/admin/images/ok.png');
});
回答by user113716
Your syntax is invalid because you forgot the functions.
您的语法无效,因为您忘记了函数。
$('[id^="matchItem_"]').each(function() {
$(this).click(function(){
//...execute my script.php?urlparam=xx....;
$(this).find('img').attr('src','/admin/images/ok.png');
});
});
Or if all you're doing is assigning the .click()
handler, you can do it without the .each()
.
或者,如果您所做的只是分配.click()
处理程序,则无需.each()
.
$('[id^="matchItem_"]').click(function(){
//...execute my script.php?urlparam=xx....;
$(this).find('img').attr('src','/admin/images/ok.png');
});
This is because most jQuery methods will automatically act on every element in the jQuery object.
这是因为大多数 jQuery 方法会自动作用于 jQuery 对象中的每个元素。
(edited to add closing parenthesis in code)
(编辑以在代码中添加右括号)