开发者

How to use inline JavaScript in HTML?

开发者 https://www.devze.com 2023-03-28 09:37 出处:网络
Support that I have this hidden field: <input type=\'hidden\' id=\'handler\' name=\'handler\' value=\'5534882394\' />

Support that I have this hidden field:

<input type='hidden' id='handler' name='handler' value='5534882394' />

And imagine that I fetch an HTML fragment from server via jQuery AJAX.

<div id='result'>
    <span></span>
</div>

However, instead of writing something like this:

$(function(){
   $('#result span').text($('#handler').val());
});

I'd like to use something like:

<div id='result'>
    <span>javascript:$('#handler').val();</span>
</d开发者_如何学运维iv>

However, I don't get the intended result. Can I use this approach with JavaScript?

Update: Everybody please, I know about $(document).ready();. So, don't provide better ways. I just wanted to know if it's possible to have inline JavaScript, or not, and if yeah, how?


No, you can't use that approach with Javascript. There is no such thing as inline Javascript.

What you see in a link like <a href="javascript:alert(1)"> is the javascript: pseudo-protocol, similar in use to the http: protocol. When you point the browser to such an URL, the browser runs the script.

If you want to run a script in the page, you need a script tag.


Although the <script> tag works and would let you do what you are trying to do, I would really suggest rethinking your design there. This is not directly what you would call "unobtrusive Javascript".

Why do you preferto mix HTML and JS? If it's for curiosity - OK, but if this is intended to turn into production code then you might want to separate the two as much as you can. You will be rewarded with a much better maintainability in the end.


You could do -

<input type="text" id="handler" value="yes"/>
<div id='result'>
    <span>
       <script>document.write($('#handler').val());</script>
    </span>
</div>

and the page would run the Javascript when it hit the script tag. You'd have to make sure that '#handler' element was already loaded though or the script would fail.

In general it would be better to keep script tags such as this away from your mark-up.

Working demo - http://jsfiddle.net/ipr101/h6zXs/


Have you forgotten about the <script> tag?

<div id="result"></div>
<script>$('#result').text($('#handler').val();</script>


A few years back, I had that exact problem: I was using AJAX to retrieve HTML and that HTML had embedded Javascript. I was never able to find a better solution than parsing the HTML manually to dig out the Javascript tags and calling eval on their contents. Hackish and unreliable, but it was the best I could find.

0

精彩评论

暂无评论...
验证码 换一张
取 消