jquery选择器不能使用Cassette处理脚本标记内的元素 [英] jquery selector does not work on element inside script tag using Cassette

查看:108
本文介绍了jquery选择器不能使用Cassette处理脚本标记内的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 $(#index)来访问data-onload时.data(onload)我回来了'undefined'

<script type="text/html">
        <section id="index" data-onload="app.load()">
            <div data-bind="text:name"></div>
        </section>
</script>

如果没有周围的脚本标记,一切正常。这是使用 Cassette 加载的,它将其包装在脚本标记内。

Without the surrounding script tag everything works fine. This is loaded using Cassette which wraps it inside script tags.

我做错了什么?

推荐答案

脚本标记的内容不是文档DOM树的一部分。如果您考虑一下,这是有道理的,因为JavaScript语法不是有效的HTML,您可以在脚本标记之间推送JavaScript。

The contents of the script tag are not part of the DOM tree for your document. If you think about it, this makes sense, since the JavaScript syntax is not valid HTML and you can just shove JavaScript in between the script tags.

通常,您不会在脚本标记内放置任何HTML。 data-onload属性中存在JavaScript不需要使用脚本标记,因此最简单的方法可能是删除脚本标记。

Typically, you wouldn't put any HTML inside a script tag. The presence of JavaScript in the data-onload attribute doesn't require the use of the script tag, so the simplest thing is probably to just erase the script tag.

On另一方面,如果您尝试使用这一块HTML作为模板,比如说客户端MVC框架。那是我唯一一次看到有意义的脚本类型=text / html。在这种情况下,您需要在模板已渲染到DOM后搜索#index部分。在此之前,这个HTML并不存在于您可以使用JQuery访问它的任何地方。

On the other hand, if you're trying to use this chunk of HTML as a template, say for a client-side MVC framework. That's the only time I've seen script type="text/html" that made sense. In this case, you'll need to search for the #index section after the template has been rendered into the DOM. Prior to that, this HTML doesn't really exist anywhere that you can access it with JQuery.

这篇关于jquery选择器不能使用Cassette处理脚本标记内的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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