我有这个jQuery代码:
$( "#editDialog" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
但我有几个id为id的div:editDialog-0,editDialog-1,....,editDialog-n。
如何为所有这些div创建一个jQuery代码,如上面那个?
答案 0 :(得分:196)
使用jquery starts with 属性选择器
$('[id^=editDialog]')
替代解决方案 - 1(强烈推荐)
更清洁的解决方案是为每个div添加一个公共类&使用
$('.commonClass')
。
但如果html标记不在您的手中,您可以使用第一个标记。因某种原因不能改变它。
替代解决方案 - 2 (如果n is a large number
,则不推荐)
(根据@Mihai Stancu的建议)
$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')
注意:如果有2个或3个选择器,并且列表没有改变,这可能是一个可行的解决方案,但它不可扩展,因为我们必须在城镇中有新ID时更新选择器。
答案 1 :(得分:21)
让我提供一个更广泛的答案,考虑你尚未提及但会发现有用的事情。
对于您当前的问题,答案是
$("div[id^='editDialog']");
插入符号(^)取自正则表达式,表示starts with
。
解决方案1
// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']");
// Selects all divs where attribute is NOT equal to value
$("div[attribute!='value']");
// Select all elements that have an attribute whose value is like
$("[attribute*='value']");
// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']");
// Select all elements that have an attribute whose value starts with 'foo' and ends
// with 'bar'
$("[attribute^='foo'][attribute$='bar']");
上面代码中的 attribute
可以更改为元素可能具有的任何属性,例如href
,name
,id
或src
。
解决方案2
使用班级
// Matches all items that have the class 'classname'
$(".className");
// Matches all divs that have the class 'classname'
$("div.className");
解决方案3
列出它们(也在之前的答案中注明)
$("#id1,#id2,#id3");
解决方案4
当你改进时,正则表达式(从未实际使用过这些,解决方案一一直是足够的,但你永远不知道!
// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});
答案 2 :(得分:3)
为所有div添加一个公共类。例如,将foo添加到所有div。
$('.foo').each(function () {
$(this).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
});
答案 3 :(得分:2)
如果您所说的所有div都以editDialog开头,那么您可以使用以下选择器:
$("div[id^='editDialog']")
或者你可以使用类选择器,如果你更容易
<div id="editDialog-0" class="editDialog">...</div>
$(".editDialog")