为什么jQuery wrap执行内联javascript [英] why is jquery wrap executing an inline javascript

查看:67
本文介绍了为什么jQuery wrap执行内联javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用内联JavaScript包装一个元素,并且该元素再次获得执行...这是 jsfiddle

I tried to wrap an element with inline javascript and it is getting execute again...here is the jsfiddle

谢谢

推荐答案

因为当JQuery包装DOM元素时,它会删除它,并将其作为新包装器元素的子元素重新插入到DOM中.如果包含内联JS,它将重新执行.这就是它的工作原理.这就是为什么您应该将JS排除在DOM之外:)

Because when JQuery wraps a DOM element, it removes it, and re-inserts it into the DOM as a child element of the new wrapper element. If it contains inline JS, it'll get re-executed. That's just how it works. That's why you should keep your JS out of the DOM :)

如果您必须在该脚本块中包含JS,一个简单的变通办法是创建一个标志侦听器/设置器,如下所示:

A simple hack work-around if you MUST have your JS in that script block is to create a flag listener/setter, like so:

 <script type='text/javascript'>
     if(window.helloworld !== true){
         alert('helloworld');
         window.helloworld = true;
     }
 </script>

http://jsfiddle.net/AlienWebguy/uk67F/2/

当然,我不建议您在生产应用程序中创建像这样的窗口属性,但是这里有概念证明,请按照自己的意愿进行操作.

Of course I wouldn't recommend creating window properties like that in your production application, but the proof of concept is there, do with it what you will.

这篇关于为什么jQuery wrap执行内联javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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