2017-02-11 64 views
-1

如何使用vanilla javascript獲取點擊輸入的值?使用onclick從輸入中獲取價值

function getvalue() { 
 
    console.log(this.val); 
 
}
<input type="text" onclick="getvalue()" value="asdf"></input> 
 
<input type="text" onclick="getvalue()" value="asdf2"></input> 
 
<input type="text" onclick="getvalue()" value="asdf3"></input>

回答

1

使用event.target.value當函數被調用event對象傳遞給函數。 event.target標識哪個元素稱爲函數。

function getvalue() { 
 
    console.log(event.target.value); 
 
}
<input type="text" onclick="getvalue()" value="asdf"></input> 
 
<input type="text" onclick="getvalue()" value="asdf2"></input> 
 
<input type="text" onclick="getvalue()" value="asdf3"></input>

3

function getvalue(t) { 
 
    console.log(t.value); 
 
}
<input onclick="getvalue(this)" value="asdf"></input> 
 
<input onclick="getvalue(this)" value="asdf2"></input>

1

使用香草JavaScript,您可以是這樣做的:

function getValue(o) { 
 
    console.log(o.value); 
 
}
<input value="asdf" onclick="getValue(this)"></input> 
 
<input value="asdf2" onclick="getValue(this)"></input> 
 
<input value="asdf3" onclick="getValue(this)"></input>
你的函數調用

0

您需要通過元素的參考作用getValue(this) ,然後通過添加點擊監聽,如function getValue(self){ /*self.stuff*/ } 使用或 你也可以做到這一點。

window.onload = function(){ 
 
elms = document.getElementsByClassName('element'); 
 
    
 
    for(var i = 0; i < elms.length; i++){ 
 
    elms[ i ].addEventListener('click', function(){ 
 
     console.log(this.value); 
 
    }) 
 
    } 
 
    
 
}
<input class="element" value="asdf" /> 
 
<input class="element" value="asdf2" /> 
 
<input class="element" value="asdf3" />