Why is it that script will run from using jquery's html but not from using innerHTML?

ぐ巨炮叔叔 提交于 2019-12-31 03:21:06

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15605519/why-is-it-that-script-will-run-from-using-jquerys-html-but-not-from-using-inner

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