pro*_*bie 102 javascript jquery
我有这个jQuery代码:
$( "#editDialog" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
Run Code Online (Sandbox Code Playgroud)
但我有几个像id这样的div:editDialog-0,editDialog-1,....,editDialog-n.
如何为所有这些div创建一个jQuery代码,如上所述?
Kri*_*hna 215
$('[id^=editDialog]')
Run Code Online (Sandbox Code Playgroud)
替代解决方案 - 1(强烈推荐)
更清晰的解决方案是为每个div添加一个公共类并使用
$('.commonClass').
但是如果html标记不在您的手中并且由于某种原因无法更改它,您可以使用第一个.
替代解决方案 - 2(不推荐,如果n is a large number)(根据@Mihai Stancu的建议)
$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')
注意:如果有2个或3个选择器,并且列表没有更改,这可能是一个可行的解决方案,但它不可扩展,因为我们必须在城镇中有新ID时更新选择器.
Luk*_*nga 28
考虑到你尚未提及但会发现有用的内容,让我提供更广泛的答案.
对于您当前的问题,答案是
$("div[id^='editDialog']");
Run Code Online (Sandbox Code Playgroud)
插入符号(^)取自正则表达式和均值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']");
Run Code Online (Sandbox Code Playgroud)
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");
Run Code Online (Sandbox Code Playgroud)
解决方案3
列出它们(也在之前的答案中注明)
$("#id1,#id2,#id3");
Run Code Online (Sandbox Code Playgroud)
解决方案4
当你改进时,正则表达式(从未实际使用过这些,解决方案一直是足够的,但你永远不会知道!
// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});
Run Code Online (Sandbox Code Playgroud)
如果您的所有 div 都如您所说的那样以 editDialog 开头,那么您可以使用以下选择器:
$("div[id^='editDialog']")
Run Code Online (Sandbox Code Playgroud)
或者,如果对您来说更容易,您可以改用类选择器
<div id="editDialog-0" class="editDialog">...</div>
$(".editDialog")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165361 次 |
| 最近记录: |