简体   繁体   English

jQuery更改我的文本

[英]jQuery change the text inside my <span>

I have following html code: 我有以下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>

now with jQuery I want to change the text inside <span> tag. 现在使用jQuery,我想更改<span>标记内的文本。 But my code doesn't work: 但是我的代码不起作用:

$('[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() in this code return 1 or 2 and I don't get any error on FireBug 此代码中的alert()返回12 ,但FireBug上没有任何错误

Use $(this) . 使用$(this) $(this) inside the event handler refers to the element on which the event has occurred. 事件处理程序中的$(this)指发生事件的元素。

$('[id^="change_user_status_account-"]').click(function () {
    $(this).text('changed');
});

I'd recommend to use a common class on both the elements and bind event using class. 我建议在两个元素上都使用一个通用类,并使用类来绑定事件。

 $('.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> 

you are missing # in selector 您在选择器中缺少#

it should be 它应该是

$("#change_user_status_account-" + id[1]).html('OK CHANGED');

or try 或尝试

$('[id^="change_user_status_account-"]').click(function () {
    $(this).html('OK CHANGED');
});

Put a # before your id 在您的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');
});

Or Just Do 或者只是做

$('[id^="change_user_status_account-"]').click(function () {
    $(this).html('OK CHANGED');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM