我有以下 html 代码:
<span id="change_user_status_account-1">
SIMPLE TEXT INSIDE SPAN
</span>
<span id="change_user_status_account-2">
SIMPLE TEXT INSIDE SPAN
</span>
现在使用 jQuery 我想更改 <span>
中的文本标签。但我的代码不起作用:
$('[id^="change_user_status_account-"]').click(function () {
var id = $(this).attr('id').split('-');
alert(id[1]);
$("change_user_status_account-" + id[1]).html('OK CHANGED');
});
alert()
在此代码中返回 1
或2
我在 FireBug
上没有收到任何错误
最佳答案
使用$(this)
。事件处理程序内的 $(this)
指的是发生事件的元素。
$('[id^="change_user_status_account-"]').click(function () {
$(this).text('changed');
});
我建议在元素上使用公共(public)类,并使用类绑定(bind)事件。
$('.sample').on('click', function() {
$(this).text(+new Date());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<span class="sample">
SIMPLE TEXT INSIDE SPAN
</span>
<span class="sample">
SIMPLE TEXT INSIDE SPAN
</span>
关于javascript - jQuery 更改我的 <span> 内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33752810/