jquery奇怪地解析自定义标签
我遇到以下问题: http://jsfiddle.net/x55LD/1/
我我正在尝试使用 jQuery 1.6 解析自定义标签。它工作正常,除非标签位于
var string = '<div><blah></blah><select><blah></blah></select></div>';
$(string).find('blah').each(function() {
console.log("Found tag!");
});
尽管存在两个
标签,但这只会记录一条消息。
I'm having problems with the following: http://jsfiddle.net/x55LD/1/
I'm trying to parse custom tags using jQuery 1.6. It's working properly, except when a tag is located within a <select>
tag. For example:
var string = '<div><blah></blah><select><blah></blah></select></div>';
$(string).find('blah').each(function() {
console.log("Found tag!");
});
This will only log one message, despite the presence of two <blah>
tags. The second <blah>
tag within the <select>
won't be recognized. Does anyone know why this might be happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,解析的不是 JavaScript 或 jQuery,而是浏览器。尽管您可能认为
当您像这样通过 jQuery 包装字符串时,内部发生的事情是 jQuery 将字符串作为临时元素的“innerHTML”传递给浏览器。浏览器期望它能够处理 HTML,因此当它看到非法标记时,它基本上会按照它想要的方式进行处理。也许某些浏览器会单独保留
标记,但其他浏览器不会。The problem is that it's not JavaScript or jQuery that does the parsing, it's the browser. Though you may consider that
<select>
tag to be your own custom deal, the browser disagrees and expects it to contain only<option>
or<optgroup>
tags.When you wrap the string up via jQuery like that, what's happening internally is that jQuery is handing the string over to the browser as the "innerHTML" of a temporary element. The browser expects that it's got HTML to work on, so when it sees illegal markup it handles it basically however it wants to. Maybe some browsers would leave the
<blah>
tag alone, but others won't.作为使用无效 HTML 的替代方法,请使用自定义属性来标记标签或存储数据,例如
然后您可以使用属性选择器:
您还可以使用 HTML5 样式属性,例如
data-something="my data"
并使用$.data
直接获取值。由于非标准标签的内容可能无论如何都会被渲染,因此这样做与仅使用带有自定义属性的 span 标签没有什么区别。我不确定您想要使用选项组内的自定义标记来准确实现什么,但我认为您不希望呈现它,所以可能在选择或特定选项上使用自定义标记可以实现你的目标。
As an alternative to using invalid HTML, use custom attributes to mark tags or store data instead, e.g.
Then you can use the attribute selector:
You can also use HTML5 style attributes like
data-something="my data"
and use the$.data
to obtain the value directly.Since the contents of a nonstandard tag is probably just going to be rendered anyway, there's no difference in doing that versus just using a span tag with a custom attribute. I'm not sure what you're trying to achieve exactly with a custom tag inside an option group, but I wouldn't think you want it to be rendered, so probably a custom tag on a the select or a specific option would achieve your goal.