Jquery [属性]选择器 [英] Jquery [attribute] Selectors
问题描述
$ b HTML
< div id =item1>< / div>
< div id =item1style =display:none; >< / div>
JS
var find = $(this).attr(id)
$('div [id =''+ find +'] ').show();
但是我想知道如何在jQuery中使用变量选择器找到一个与变量值类似的字符串,即从上面的例子中找到一个元素,但查找#item1div,其中事件目标仍然是#item1
HTML
< div id =item1>< / div>
< div id =item1divstyle =display:none;>< / div>
JS
var find = $(this).attr (id)
$('div [id =''+ find +div']')。show() ; //语法不正确
所以我的问题是:如何纠正上述语法在属性检查中包含一个额外的字符串?
我找不到任何正确的语法参考如何添加编译字符串的值一个变量和一个显式字符串,然后检查它是否为x属性的值。
我知道我可以使用 [id * =''+ find + ']
在这里,因为替代id包含与基本字符相同的字符,但我想知道如何根据第一个id指定特定的其他id。例如,如果我有#item1,#item1div和#item1img,如何使用#item1上的事件来查找等于item1div和/或item1img的属性值
编辑:我也意识到我可以使用 [id | =''+ find +']
div相应地带有连字符,但是又不能解决具有不同结尾的id(或者连字符后面出现的不同字符串)
$('div [id ='+ find +div']')
无效 Javascript 语法:
$(// jQuery函数
'div [id =''// String
+ find // Add变量
+div//添加字符串
']'//意外字符串! - 错误
有效语法的一个例子是:
$ b $ $ p $ $ $''' 'div']'')
然而,因为它是一个id,所以可以使用id选择器:
$('div#'+ find +'div')
So I've seen several posts explaining how to use a variable in a value for attribute selection. i.e. (where the JS event refers to the div (making it $(this):
HTML
<div id="item1"></div>
<div id="item1" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+'"]').show();
But I would like to know how to use a variable in a jquery selector to find something with a similar string to the value of the variable. i.e. finding an element from the example above but looking for "#item1div", where the event target is still "#item1"
HTML
<div id="item1"></div>
<div id="item1div" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+"div"'"]').show(); // incorrect syntax
So my question is: How do I correct the above syntax to include an additional string in the attribute check?
I can't find any reference to the correct syntax for how to add compile a string of the value of a variable and an explicit string then check that as the value for x attribute.
I know I can use [id*="'+find+'"]
here because the alternate id contains the same characters as the basic one, but I want to know how to target a specific other id based on the first one. For example if I had #item1, #item1div, and #item1img, how can I use an event on "#item1" to find attribute values equal to "item1div" and/or "item1img"
EDIT: I also just realized I can just use [id|="'+find+'"]
if I name the divs accordingly with hyphens, but again doesn't solve ids with different endings (or different strings that come after the hyphen)
$('div[id="'+find+"div"'"]')
isn't valid Javascript syntax:
$( // jQuery function
'div[id="' // String
+ find // Add variable
+ "div" // Add String
'"]' // Unexpected string! - Error
One example of valid syntax would be:
$('div[id="'+find+'div"]')
However, since it's an id, you can use the id selector instead:
$('div#'+find+'div')
这篇关于Jquery [属性]选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!