Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - 使用纯JavaScript获取DOM元素值(Getting DOM element value using pure JavaScript)

Is there any difference between 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)" /> 

  ask by Adam translate from so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(这两种解决方案现在都是等效的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...