我看到我是否可以避免编写单独的功能来处理单独的按钮点击。如果我可以读取被单击的按钮的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());
答案 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
getElementsByClassName
或getElementsById
从页面中检索任何元素,并可以访问其所有元素。 name
,value
,innerHTML
等等......
来自任何浏览器控制台的StackOverflow示例(F12打开):
var button = document.getElementById("submit-button");
//this only works if the button has id="submit-button"
button.value;
// output : "Text in button"