[英]jQuery change the text inside my <span>
我有以下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');
});
我建議在兩個元素上都使用一個通用類,並使用類來綁定事件。
$('.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>
您在選擇器中缺少#
它應該是
$("#change_user_status_account-" + id[1]).html('OK CHANGED');
或嘗試
$('[id^="change_user_status_account-"]').click(function () {
$(this).html('OK CHANGED');
});
在您的id
前加#
$('[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');
});
或者只是做
$('[id^="change_user_status_account-"]').click(function () {
$(this).html('OK CHANGED');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.