为什么脚本会使用jquery的html运行,但不能使用innerHTML? [英] Why is it that script will run from using jquery's html but not from using innerHTML?
问题描述
所以我在这里有点困惑。我不明白为什么脚本在与jquery的 .html()
放置时执行,但不与 innerHTML
放置。我查看了jQuery的 .html
的源代码,它似乎仍在使用 innerHTML
。任何人都可以解释这种行为吗?
我在ajax响应中遇到过这个问题。我找回了html和一个脚本
标签,其中包含一些javascript,我通常使用 html
,但对于某些原因曾使用 innerHTML
这次认为没有区别。
我知道这可能是本地化的,所以我做了一个jsFiddle,其超时类似于ajax响应,以突出问题。
尽管我可以通过一些断点来判断,但jQuery会尝试使用 innerHTML
,但如果失败了,它会回退到清空目标元素,并通过DOM附加新内容。
更新:请参阅下面的Felix Kling的评论;基本上,如果要插入的字符串内容包含脚本或样式/链接标记,jQuery将不会直接使用 innerHTML
当发生这种情况时(并且在您的情况下),内容会经过一个称为 domManip
的函数,但我并不认为它完全理解,但它特别是查找和评估脚本。
所以简短的回答是:jQuery毕竟不使用 innerHTML
。希望我能够更好地一步一步地了解发生了什么,但我不知道我的方式是否足够好。我只是设置了一个断点(在jQuery-1.9.1.js中的6074行; jQuery决定使用 innerHTML
的 not )并绕过源头一点。
So I am a little confounded here. I do not understand why script executes when placed with jquery's .html()
but not with innerHTML
. I looked at the source code for jQuery's .html
and it still seemed that innerHTML
was being used. Can anyone explain this behavior?
I came across this during an ajax response. I was getting back html and a script
tag with some javascript in it, and I usually use html
, but for some reason had used innerHTML
this time thinking there was no difference.
I understand that this might seem to be localized, so I made a jsFiddle with a timeout that behaves similar to an ajax response in order to highlight the issue.
jsFiddle demonstrating the behavior
As far as I can tell from a bit of breakpointin', jQuery will try to use innerHTML
, but, failing that, it'll fall back to emptying the target element, and appending the new content via the DOM.
Update: see Felix Kling's comment below; basically, if the string content to be inserted contains script or style/link tags, jQuery won't use straight innerHTML
When that happens - and it does in your case - the content goes through a function called domManip
which I don't claim to fully understand, but it does specifically look for and evaluate scripts.
So the short answer is: jQuery's not using innerHTML
after all. Wish I could give you a better step-by-step of exactly what happens, but I don't know my way around jQuery's source well enough. I just set a breakpoint (at line 6074 in jQuery-1.9.1.js; the point where jQuery decides not to use innerHTML
after all) and stepped around the source a little.
这篇关于为什么脚本会使用jquery的html运行,但不能使用innerHTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!