问题
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