[英]jQuery selector with specific attribute
I've got this code: 我有这个代码:
$('a').click(
function() {
$("#change_flash").css("display", "block"); $("#my_flash").css("display", "none");
});
But this one works for all anchor elements. 但是这个适用于所有锚元素。 I would like to influence with this script only for anchors elements which contains rel="lightbox" attribute. 我想用这个脚本来影响包含rel =“lightbox”属性的锚点元素。
How can I achieve it? 我怎样才能实现它?
$('a[rel="lightbox"]').click(
function() {
$("#change_flash").css("display", "block"); $("#my_flash").css("display", "none");
});
Use the following: 使用以下内容:
$('a[rel="lightbox"]').click(
function(){
// do your stuff here
});
This is using the attribute="value"
notation (see references). 这是使用attribute="value"
表示法(请参阅参考资料)。
There are, also, other options: 还有其他选择:
attribute^="value"
, attribute-begin-with: attribute^="value"
, attribute$="value",
attribute-ends-with: attribute$="value",
Note, of course, that while $('[rel="lightbox"]')
is an absolutely valid selector all by itself, this will cause jQuery to examine every element on the page for that attribute and value in order to bind/assign the click
event(s); 当然要注意,虽然$('[rel="lightbox"]')
本身就是一个绝对有效的选择器,但这会导致jQuery检查页面上该属性和值的每个元素,以便绑定/赋值click
事件; therefore it's always best to use a tag-name, hence the $('a[rel="lightbox"]')
, or a class-name in order to limit the number of elements jQuery has to search through to find the matching elements. 因此,最好使用标签名称,因此使用$('a[rel="lightbox"]')
或类名来限制jQuery必须搜索的元素数量以查找匹配元素。
Although in modern browsers I seem to remember this 'search' is handed over to the native document.querySelectorAll()
, rather than using Sizzle, but even so it's best to limit the amount of work a browser need do. 虽然在现代浏览器中我似乎记得这个'搜索'被移交给原始document.querySelectorAll()
,而不是使用Sizzle,但即便如此,最好限制浏览器需要做的工作量。
References: 参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.