Getting DOM element value using pure JavaScript

前端 未结 5 2042
迷失自我
迷失自我 2020-11-28 06:36

Is there any difference between these solutions?

Solution 1:

5条回答
  •  旧巷少年郎
    2020-11-28 07:09

    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.

    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.

    It makes the most sense to just pass the element with this instead of fetching it again with its ID.

提交回复
热议问题