使用纯 JavaScript 获取 DOM 元素值
这些解决方案之间有什么区别吗?
解决方案一:
function doSomething(id, value) {
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
...以及解决方案 2:
function doSomething(id) {
var value = document.getElementById(id).value;
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id)" />
Is there any difference between these solutions?
Solution 1:
function doSomething(id, value) {
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
...and Solution 2:
function doSomething(id) {
var value = document.getElementById(id).value;
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id)" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
更新:问题已被编辑。现在这两种解决方案是等效的。
原始答案
是,最值得注意的是!我认为第二个不会起作用(如果可以的话,也不是很便携)。第一个应该没问题。
这也应该有效。
Update: The question was edited. Both of the solutions are now equivalent.
Original answer
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.
This should also work.
第二个功能应该有:
那么它们基本上是相同的功能。
The second function should have:
Then they are basically the same function.
在第二个版本中,您传递从
this.id
返回的字符串。不是元素本身。所以 id.value 不会给你你想要的。
您需要使用
this
传递元素。然后:
注意:在某些浏览器中,如果您这样做,第二个也可以工作:
因为元素 ID 是全局属性,但是这并不安全。
最有意义的做法是仅使用
this
传递元素,而不是使用其 ID 再次获取它。In the second version, you're passing the String returned from
this.id
. Not the element itself.So
id.value
won't give you what you want.You would need to pass the element with
this
.then:
Note: In some browsers, the second one would work if you did:
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with
this
instead of fetching it again with its ID.传递对象:
您可以从对象获取所有数据:
或仅传递
id
:获取对象及其后的值:
Pass the object:
You can get all data from object:
Or pass the
id
only:Get the object and after that value:
如果我们看效果的话,没有什么区别——价值是一样的。然而还有更多...
解决方案 3:
如果DOM元素有id那么你可以直接在js中使用它
There is no difference if we look on effect - value will be the same. However there is something more...
Solution 3:
if DOM element has id then you can use it in js directly
这也应该有效。
This should also work.