[英]Getting the value from the button in html
我有一个html组件按钮,例如
<button>Add to cart</button>
现在,我想在按钮中添加文本,即“添加到购物车”。
我如何在脚本中获取此值。 在单击此按钮时,会将事件传递给Windows单击事件监听器。 在里面,我想获得这个价值。
这是我的剧本
<script type="text/javascript">
window.addEventListener('click',function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log('window noticed you clicked something1');
console.log("value of the element clicked== "+target.text());
console.log(target);//<-- this is the element that was clicked
}, false);
</script>
如果只有一个按钮,则可以尝试getElementsByTagName
;如果您有多个按钮,则可以定义id并使用document.getElementById
console.log(document.getElementsByTagName("button")[0].innerHTML); console.log(document.getElementById("myButton").innerHTML);
<button>Add to Cart</button> <button id="myButton">Add to Cart2</button>
首先,您需要在<script>
之外编写HTML。 其次,您需要单击按钮,因此为按钮分配一个id
,然后在其上绑定单击事件。 HTML将是
<button id='addToCart'>Add to cart</button>
和JavaScript将是
document.getElementById('addToCart').addEventListener('click',function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
console.log('window noticed you clicked something1');
console.log("value of the element clicked== "+target.innerText);
console.log(target);//<-- this is the element that was clicked
}, false);
这是工作中的JSFIDDLE
您也可以像这样使用innerHTML
console.log("value of the element clicked== "+target.innerHTML);
尝试这个 :-
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <button class="myButton">Add to cart</button> <script> var buttonValue = document.getElementsByClassName("myButton")[0].innerHTML; console.log(buttonValue); window.addEventListener('click',function(e) { e = e || window.event; var target = e.target || e.srcElement; console.log('window noticed you clicked something1'); console.log("value of the element clicked== "+target.innerHTML); console.log(target);//<-- this is the element that was clicked }, false); </script> </body> </html>
尝试读取按钮的值。
console.log(target.value);//<-- this is the element that was clicked
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.