我有一个按钮:
<button type="button" onclick="toggleColor('white');" >White</button>
这使得:
有没有办法使用jQuery获取按钮上写的内容。例如,此按钮将返回White
,因为它位于2个按钮标签之间。
像这样在你的按钮上添加id
<button type="button" onclick="toggleColor('white');" id="your_button_id" >White</button>
现在你可以像这样使用JS了
var button_text = document.getElementById('your_button_id').innerHTML;
你也可以像这样使用JQUERY
var button_text = $('#your_button_id').text();
尝试
$("button").click(function(){
var title=$(this).attr("value");
alert(title);
});
给按钮一个ID
<button id="btnTest" type="button" onclick="toggleColor('white');" >White</button>
JQuery的:
alert($("#btnTest").text());
您可以在添加ID后使用Vanilla JS执行此操作,以便获取元素。
假设:
<button type="button" onclick="toggleColor('white');" id='myButton'>White</button>
你可以用JavaScript做:
var someVar = document.getElementById('myButton').innerHTML; // -> White
var anotherVar = document.getElementById('myButton').textContent; // -> White
两者都将举行“白色”
只需为按钮提供一个id,并将其与JQuery一起使用
<button id=btn type="button" onclick="toggleColor('white');" >White</button>
然后像这样使用jquery
$("#btn").val();
它会适合你的情况。
试试这个event.target
$("button").click(function(event){
var text=$(event.target).attr("value")
alert(text);
});
这对我有用铬。
$("#your-button-id").val();