jquery selector does not work on element inside script tag using Cassette

ぃ、小莉子 提交于 2019-12-23 16:55:50

问题


When trying to access data-onload using $("#index").data("onload") I get back 'undefined':

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

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

What am I doing wrong?


回答1:


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.

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 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.




回答2:


Script elements that have an unknown content-type and it's going to be ignored.
The browser does not know what to do with a text/html type script.

You just need:

    <section id="index" data-onload="YourTextValue">
        <div data-bind="YourTextValue"></div>
    </section>



回答3:


As far as I know, the code inside the <script> - Tag is usually compiled as Javascript and is not part of the DOM. And I'm not sure if the <script type="text/html"> is even a valid tag/attribute combination.

Remove the script tag, you don't need it.



来源:https://stackoverflow.com/questions/10575461/jquery-selector-does-not-work-on-element-inside-script-tag-using-cassette

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!