使用纯 JavaScript 获取 DOM 元素值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4173391/
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
Getting DOM element value using pure JavaScript
提问by Adam
Is there any differencebetween these solutions?
这些解决方案之间有什么区别吗?
Solution 1:
解决方案1:
function doSomething(id, value) {
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
...and Solution 2:
...和解决方案2:
function doSomething(id) {
var value = document.getElementById(id).value;
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id)" />
回答by yorick
Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.
是的,最值得注意的是!我认为第二个行不通(如果行得通,也不是很便携)。第一个应该没问题。
// HTML:
<input id="theId" value="test" onclick="doSomething(this)" />
// JavaScript:
function(elem){
var value = elem.value;
var id = elem.id;
...
}
This should also work.
这也应该有效。
Update: the question was edited. Both of the solutions are now equivalent.
更新:问题已编辑。这两个解决方案现在是等价的。
回答by Evan Mulawski
The second function should have:
第二个函数应该有:
var value = document.getElementById(id).value;
Then they are basically the same function.
那么它们的功能基本相同。
回答by user113716
In the second version, you're passing the String returned from this.id
. Not the element itself.
在第二个版本中,您将传递从this.id
. 不是元素本身。
So id.value
won't give you what you want.
所以id.value
不会给你你想要的。
You would need to pass the element with this
.
您需要使用this
.
doSomething(this)
then:
然后:
function(el){
var value = el.value;
...
}
Note: In some browsers, the second one would work if you did:
注意:在某些浏览器中,如果您执行以下操作,则第二个会起作用:
window[id].value
because element IDs are a global property, but this is not safe.
因为元素 ID 是一个全局属性,但这并不安全。
It makes the most sense to just pass the element with this
instead of fetching it again with its ID.
只传递元素this
而不是用它的 ID 再次获取它是最有意义的。
回答by R. Z.
Pass the object:
传递对象:
doSomething(this)
You can get all data from object:
您可以从对象获取所有数据:
function(obj){
var value = obj.value;
var id = obj.id;
}
Or pass the id
only:
或者通过id
唯一的:
doSomething(this.id)
Get the object and after that value:
获取对象并在该值之后:
function(id){
var value = document.getElementById(id).value;
}
回答by Kamil Kie?czewski
There is no difference if we look on effect - value will be the same. However there is something more...
如果我们看效果没有区别 - 价值将是相同的。然而,还有更多……
Solution 3:
解决方案3:
function doSomething() {
console.log( theId.value );
}
<input id="theId" value="test" onclick="doSomething()" />
if DOM element has id then you can use it in js directly
如果 DOM 元素有 id 那么你可以直接在 js 中使用它