jquery奇怪地解析自定义标签

发布于 2024-11-09 21:08:02 字数 532 浏览 0 评论 0原文

我遇到以下问题: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心不设防 2024-11-16 21:08:02

问题是,解析的不是 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.

国产ˉ祖宗 2024-11-16 21:08:02

作为使用无效 HTML 的替代方法,请使用自定义属性来标记标签或存储数据,例如

<div><span blah></span><select blah></select></div>

然后您可以使用属性选择器:

$('[blah]')...

您还可以使用 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.

<div><span blah></span><select blah></select></div>

Then you can use the attribute selector:

$('[blah]')...

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文