我创建一个带有附加项的按钮
var row = '<tr><td><button class="directly-follow btn" text="Follow">Follow</button></td></tr>';
$('.textWord_about> table > tbody').append(row);我希望通过单击按钮来使用jquery更改按钮文本。
这就是我在做什么:
$(document).on('click', '.directly-follow', function() {
event.preventDefault();
var $post = $(this);
if ($post.attr("text") == "Follow") {
$post.text('Unfollow');
//do something
}
else{
$post.text('Follow');
//do something
}问题是,行$post.text('Unfollow')更改按钮文本,但不更改html标记(text="Follow")中定义的文本。因此,该功能不会按我所希望的那样切换。( if始终为真!)
如何使用jquery更改文本?
发布于 2017-08-23 19:18:37
要更改自定义attribute的值,必须使用attr方法。
可以使用attr方法获取attribute值,也可以设置attribute值。
该方法获取匹配元素集中第一个元素的属性值,或为每个匹配元素设置一个或多个属性。
$(document).on('click', '.directly-follow', function() {
event.preventDefault();
var $post = $(this);
if ($post.attr("text") == "Follow") {
$post.text('Unfollow');
$post.attr('text','Unfollow');
}
else{
$post.text('Follow');
$post.attr('text','Follow');
}发布于 2017-08-23 19:25:39
使用attr代替文本。http://api.jquery.com/attr/
var row = '<tr><td><button class="directly-follow btn" text="Follow">Follow</button></td></tr>';
$('.textWord_about> table > tbody').append(row);
$(document).on('click', '.directly-follow', function() {
event.preventDefault();
if ($(this).attr("text") == "Follow") {
$(this).text('Unfollow');
$(this).attr('text','Unfollow');
}
else{
$(this).text('Follow');
$(this).attr('text','Follow');
}
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="textWord_about">
<table>
<tbody>
</tbody>
</table>
</div>
发布于 2017-08-23 19:28:22
我想你想要这样:
var row = '<tr><td><button class="directly-follow btn" text="Follow">Follow</button></td></tr>';
$('.textWord_about> table > tbody').append(row);
$(document).on('click', '.directly-follow', function(event) {
event.preventDefault();
var $post = $(this);
console.log($post.attr("text"))
if ($post.attr("text") == "Follow") {
$post.text('Unfollow');
$post.attr("text","Unfollow")
//do something
}
else{
$post.text('Follow');
$post.attr("text","Follow")
//do something
}
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='textWord_about'>
<table>
<tbody></tbody>
</table>
</div>
<div class='directly-follow'>
</div>
https://stackoverflow.com/questions/45847735
复制相似问题