Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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>

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top