开发者

Change text with jQuery

I need to change the text within a link on click from 'open' to 'close'.

<a href="#" id="clickMe"><span class="A open"></span>open</a>

But how do I change the label after I run an AJAX function on success?

success: function(){
   $("#clickMe").find("span").toggleClass("open close");开发者_如何学Go
   // toggle label 
}


You could modify the actual TextNode contents as well by using contents() and the right index:

   var s = $("#clickMe").find("span").toggleClass("open close").attr('class'); 
    s = s.replace("A","").replace(" ",""); // get rid of the other class for the text to be used
   $("#clickMe").contents()[1].nodeValue = s;   

or the same thing in a single line:

$("#clickMe").contents()[1].nodeValue = $("#clickMe").find("span").toggleClass("open close").attr('class').replace("A","").replace(" ","");   

edit

If you wanna use some other texts than the class names, you could do it like this:

$('button').click(function(){
   var s = $("#clickMe").find("span").toggleClass("open close").hasClass('open'); 
    if (s) s = "Open text";
    else s = "Closed text";

   $("#clickMe").contents()[1].nodeValue = s;

}); 

example: http://jsfiddle.net/niklasvh/ULsx4/13/

example (1): http://jsfiddle.net/niklasvh/ULsx4/ & single line: http://jsfiddle.net/niklasvh/ULsx4/12/


If you want to change the text use could use the .html() method:

$("#clickMe").html("<span class=\"close\"></span>close");

And if you want to leave the span untouched:

$('#clickMe').contents().filter(function() {
    return this.nodeType == 3;
}).replaceWith('close');


Try $("#clickMe span").text("my text")


$('#clickMe').contents().filter(function() {   
    return this.nodeType == 3;
}).get(0).nodeValue = 'Hello';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜