淘汰赛 - 如何获得按钮的文字值?

时间:2016-10-09 02:49:51

标签: javascript button text knockout.js

我看到我是否可以避免编写单独的功能来处理单独的按钮点击。如果我可以读取被单击的按钮的Text值,那么我可以使用一个名为" showName"的函数。并使用switch语句处理每个相应的按钮单击。

这可能吗?

<body>
    <button data-bind="click: showName">Show Name</button>
    <button data-bind="click: showName">Show Lists</button>
</body>

我尝试了以下各种方法。我想得到价值&#34;显示名称&#34;如果单击第一个按钮。但这些都不起作用。

function TutorialsViewModel(){
    this.showName = function(e){           
        console.log(e);
        console.log(e.target);
        console.log(e.target.value);
    };   
}

ko.applyBindings(new TutorialsViewModel());

2 个答案:

答案 0 :(得分:3)

您需要使用e.target.value

,而不是使用e.target.innerText

这是一个有效的演示http://jsfiddle.net/e8JPT/315/

<强> HTML

<body>
    <button id="btn1" data-bind="click: log">Show Name</button>
    <button id="btn2" data-bind="click: log">Show Lists</button>
</body>

<强>的Javascript

var TutorialsViewModel=function(){
    this.log = function(data, event){           

        alert("You clicked on : " +event.target.innerText);
    };   
}

ko.applyBindings(new TutorialsViewModel());

希望这有帮助!

答案 1 :(得分:0)

使用stackoverflow作为示例,您可以使用函数getElementsByName getElementsByClassNamegetElementsById从页面中检索任何元素,并可以访问其所有元素。 namevalueinnerHTML等等......

来自任何浏览器控制台的StackOverflow示例(F12打开):

var button = document.getElementById("submit-button"); 
//this only works if the button has id="submit-button"
button.value;
// output : "Text in button"