内联 Javascript(在 HTML 中)如何工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10607847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does inline Javascript (in HTML) work?
提问by Steven Lu
I know this is bad practice. Don't write code like this if at all possible.
我知道这是不好的做法。如果可能的话,不要写这样的代码。
Of course, we'll always find ourselves in situations where a clever snippet of inline Javascript can address an issue quickly.
当然,我们总是会发现自己处于这样的情况:一个巧妙的内联 Javascript 片段可以快速解决问题。
I am pursuing this query in the interest of fully understanding what happens (and the potential pitfalls) when something like this is written:
我追求这个查询是为了完全理解写这样的东西时会发生什么(和潜在的陷阱):
<a href="#" onclick="alert('Hi')">Click Me</a>
As far as I can tell this is functionally the same as
据我所知,这在功能上与
<script type="text/javascript">
$(function(){ // I use jQuery in this example
document.getElementById('click_me').onclick =
function () { alert('Hi'); };
});
</script>
<a href="#" id="click_me">Click Me</a>
Extrapolating from this it seems that the string assigned to attribute onclick
is inserted within an anonymous function which is assigned to the element's click handler. Is this actually the case?
由此推断,分配给属性的字符串似乎onclick
插入到分配给元素单击处理程序的匿名函数中。实际情况是这样吗?
Because I'm starting to do things like this:
因为我开始做这样的事情:
<a href="#" onclick="$(this).next().fadeIn(); return false;">Display my next sibling</a> <!-- Return false in handler so as not to scroll to top of page! -->
Which works. But I don't know how much of a hack this is. It looks suspicious because there is no apparent function that is being returned from!
哪个有效。但我不知道这是多少黑客。它看起来很可疑,因为没有明显的函数正在返回!
You might ask, why are you doing this, Steve? Inline JS is bad practice!
你可能会问,你为什么要这样做,史蒂夫?内联 JS 是不好的做法!
Well to be quite honest I'm tired of editing three different sections of code just to modify one section of a page, especially when I'm just prototyping something to see if it will work at all. It is so much easier and sometimes even makes sense for the code specifically related to this HTML element to be defined right withinthe element: When I decide 2 minutes later that this was a terrible, terrible idea I can nuke the entire div (or whatever) and I don't have a bunch of mysterious JS and CSS cruft hanging around in the rest of the page, slowing down rendering ever so slightly. This is similar to the concept of locality of reference but instead of cache misses we're looking at bugs and code bloat.
老实说,我厌倦了编辑三个不同的代码部分只是为了修改页面的一个部分,尤其是当我只是在制作原型以查看它是否有效时。它是如此容易得多,有时甚至还为具体涉及到这个HTML元素的代码的含义来定义权范围内的元素:当我决定2分钟后,这是一个可怕的,可怕的想法我可以攻击整个股利(或任何) 并且我在页面的其余部分没有一堆神秘的 JS 和 CSS 杂物,从而稍微减慢了渲染速度。这类似于引用局部性的概念,但我们关注的是错误和代码膨胀,而不是缓存未命中。
采纳答案by apsillers
You've got it nearly correct, but you haven't accounted for the this
value supplied to the inline code.
您几乎正确,但您没有考虑this
提供给内联代码的值。
<a href="#" onclick="alert(this)">Click Me</a>
is actually closer to:
实际上更接近于:
<a href="#" id="click_me">Click Me</a>
<script type="text/javascript">
document.getElementById('click_me').addEventListener("click", function(event) {
(function(event) {
alert(this);
}).call(document.getElementById('click_me'), event);
});
</script>
Inline event handlers set this
equal to the target of the event.
You can also use anonymous function in inline script
内联事件处理程序设置为this
等于事件的目标。您还可以在内联脚本中使用匿名函数
<a href="#" onclick="(function(){alert(this);})()">Click Me</a>
回答by Pointy
What the browser does when you've got
当你有浏览器时,浏览器会做什么
<a onclick="alert('Hi');" ... >
is to set the actual value of "onclick" to something effectively like:
是将“onclick”的实际值有效地设置为:
new Function("event", "alert('Hi');");
That is, it creates a function that expects an "event" parameter. (Well, IE doesn't; it's more like a plain simple anonymous function.)
也就是说,它创建了一个需要“事件”参数的函数。(嗯,IE 没有;它更像是一个简单的匿名函数。)
回答by Daniel B
There seems to be a lot of bad practicebeing thrown around Event Handler Attributes. Bad practice is not knowing and using available features where it is most appropriate. The Event Attributes are fully W3C Documented standards and there is nothing bad practice about them. It's no different than placing inline styles, which is also W3C Documented and can be useful in times. Whether you place it wrapped in script tags or not, it's gonna be interpreted the same way.
似乎有很多关于事件处理程序属性的不好的做法。不好的做法是不知道和使用最合适的可用功能。事件属性完全是 W3C 文档化的标准,没有什么不好的做法。这与放置内联样式没有什么不同,内联样式也是 W3C 记录的并且有时会很有用。无论你是否将它包裹在脚本标签中,它都会以相同的方式被解释。
https://www.w3.org/TR/html5/webappapis.html#event-handler-idl-attributes
https://www.w3.org/TR/html5/webappapis.html#event-handler-idl-attributes
回答by aziz punjani
The best way to answer your question is to seeit in action.
回答您的问题的最佳方法是查看它的实际效果。
<a id="test" onclick="alert('test')"> test </a> ?
In the js
在js中
var test = document.getElementById('test');
console.log( test.onclick );
As you see in the console
, if you're using chrome it prints an anonymous function with the event object passed in, although it's a little different in IE.
正如您在 中看到的console
,如果您使用的是 chrome,它会打印一个带有传入事件对象的匿名函数,尽管它在 IE 中略有不同。
function onclick(event) {
alert('test')
}
I agree with some of your points about inline event handlers. Yes they are easy to write, but i don't agree with your point about having to change code in multiple places, if you structure your code well, you shouldn't need to do this.
我同意你关于内联事件处理程序的一些观点。是的,它们很容易编写,但我不同意您关于必须在多个地方更改代码的观点,如果您的代码结构良好,则不需要这样做。
回答by Dagg Nabbit
Try this in the console:
在控制台中试试这个:
var div = document.createElement('div');
div.setAttribute('onclick', 'alert(event)');
div.onclick
In Chrome, it shows this:
在 Chrome 中,它显示:
function onclick(event) {
alert(event)
}
...and the non-standard name
property of div.onclick
is "onclick"
.
... 的非标准name
属性div.onclick
是"onclick"
。
So, whether or not this is anonymous depends your definition of "anonymous." Compare with something like var foo = new Function()
, where foo.name
is an empty string, and foo.toString()
will produce something like
因此,这是否匿名取决于您对“匿名”的定义。与类似的东西比较var foo = new Function()
, wherefoo.name
是一个空字符串,并foo.toString()
会产生类似的东西
function anonymous() {
}
回答by mattytommo
It looks suspicious because there is no apparent function that is being returned from!
它看起来很可疑,因为没有明显的函数正在返回!
It is an anonymous function that has been attached to the click event of the object.
它是一个匿名函数,已附加到对象的单击事件。
why are you doing this, Steve?
你为什么要这样做,史蒂夫?
Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)
你到底为什么要.....啊没关系,正如你所提到的,这确实是被广泛采用的坏习惯:)