如何找到< script>具有“类型"的特定值的元素.属性? [英] How to find <script> elements with particular value of "type" attribute?

查看:98
本文介绍了如何找到< script>具有“类型"的特定值的元素.属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在随机HTML文档中假定以下脚本标签:

Assuming the following script tag in a random HTML document:

<script id="target" type="store">
    //random JavaScript code
    function foo(){
       alert("foo");
    }
    foo();
</script>

任何人都可以解释为什么下面的表达式找不到其type属性的值为storescript所有元素.

can anybody explain why the following expression doesn't find all elements of script with value store for their type attribute.

var sel = $('#target script[type="store"]');

jQuery版本:v1.7.2 Chrome版本:25.0.1364.172(在Debian Squeeze上运行)

jQuery version: v1.7.2 Chrome version: 25.0.1364.172 (running on Debian Squeeze)

推荐答案

您的选择器$('#target script[type="store"]')将匹配类型为store的任何脚本标记,该脚本标记是ID为target的元素的子代.您的示例HTML并非如此.

Your selector $('#target script[type="store"]') would match any script tag with type store that is a child of the element with id target. Which isn't the case for your example HTML.

如果要选择类型为store的所有脚本标签,则选择器应如下所示:$('script[type="store"]').

If you want to select all script tags with type store, your selector should look something like this: $('script[type="store"]').

如果只想选择ID为target的特定脚本标记,则只能使用$('#target').无需更具体,因为ID对于该元素应该是唯一的.仅使用ID选择器也将更加高效,因为jQuery然后可以利用本机document.getElementById()选择元素(也许是微优化,但仍然...)

If you only want to select the particular script tag that has id target, you could use $('#target') only. No need to be more specific as the ID should be unique to that element. Using only the ID selector would be more efficient as well, since jQuery then could utilize the native document.getElementById() to select your element (a micro-optimization perhaps, but still...)

这篇关于如何找到&lt; script&gt;具有“类型"的特定值的元素.属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆