从html中的按钮获取值

时间:2017-06-28 09:55:10

标签: javascript 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>

4 个答案:

答案 0 :(得分:0)

如果您只有一个按钮,则可以尝试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>

答案 1 :(得分:0)

首先,您需要在<script>之外编写HTML。其次,您需要单击按钮,然后为按钮分配id,然后在其上绑定click事件。 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);

答案 2 :(得分:0)

试试这个: -

<!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>

答案 3 :(得分:0)

尝试读取按钮的值。

    console.log(target.value);//<-- this is the element that was clicked