开发者

jquery 1.2.7 how can I replace some text?

I cannot upgrade my jQuery, and I was wondering why this function is not existin开发者_StackOverflow社区g. How can I implement this:

$('#block-block-1 .content').replace(/^\s*|\s*$/g,'');

What I get is: "function doesn't exist"

thanks


If I'm reading this right, you want to change the text of that particular element. You can do this using the .text method. We use element.text() to retrive the text and element.text(newText) to set it. We can combine both to alter it.

var content = $('#block-block-1 .content');
content.text(content.text().replace(/^\s*|\s*$/g,''));

If you want to work with multiple elements, you can use the .each method to operate on each one separately.

$('#block-block-1 .content').each(function(content) {
    content.text(content.text().replace(/^\s*|\s*$/g,''));
});


.replace() is a member of JavaScript's string object, not a jQuery object. Therefore, you need to get the text of the jQuery object, change it, and update the jQuery object:

var content = $('#block-block-1 .content');
var text = content.text();
var replacedText = text.replace(/^\s*|\s*$/g,'');
content.text(replacedText);

Or, using text(function(index, text)), a better way:

$('#block-block-1 .content').text(function(index, text) {
    return text.replace(/^\s*|\s*$/g,'');
});

EDIT:

Darn, the second one's jQuery 1.4 only.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜