我们可以在jquery中循环类似的事件

时间:2013-07-19 09:38:24

标签: jquery html

具体..代码

$("#ht_1").click(function () {
    alert("hello");
});

$("#ht_2").click(function () {
    alert("hello");
});

// what i tried
for (i = 1; i <= 2; i++) {
    $("#ht_" + i).click(function () {
        alert("hello");
    });
}

这段代码有什么问题,这样做有什么选择?

编辑:抱歉

5 个答案:

答案 0 :(得分:4)

您的代码意图ht_1, ht_2是一个标签,但似乎是id,您可以使用attribute selector , starts with

<强> Live Demo

语法: jQuery( "[attribute^='value']" )

$('*[id^="ht_"]').click(function(){
    alert("hello");
});

您可以在此jQuery api link上找到不同的有用选择器,例如contains,ends with,stats with,equal等。

答案 1 :(得分:3)

您可以为要使用单击功能的所有元素指定一个类。

示例:

/** CSS fragment **/
$(".htClass").click(function(){
    alert("hello");
});


<!-- html fragment -->
<div class="htClass">content 1</div>
<div class="htClass anotherClass">content 2</div>
<!-- here, another class is additionally assigned -->

只需将htClass分配给您希望执行特定功能的任何元素。

答案 2 :(得分:1)

对于id以ht

开头的元素,您可以使用如下所示的选择器
$("[id^='ht_']").click(function(){
});

答案 3 :(得分:0)

那些不是选择者......很可能你需要$(“。ht _”+ i)或$(“#ht _”+ i)......除此之外,它应该适用于IMO。

答案 4 :(得分:0)

什么是ht_1?对于课程,您需要使用.ht_1,ID应为#ht_1。如果你有很多类似的元素,$.live可能是个不错的选择。