最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery each replace innerHtml - Stack Overflow

programmeradmin3浏览0评论

Jquery

I am trying to change the inner text on multiple td element which I believe should look something like this although this does not appear to be a jquery object when I am debugging (I could be wrong).

What is the correct way this should be done?

$('.leg-number').each(function () {
        this.html('foo');
    });

Jquery

I am trying to change the inner text on multiple td element which I believe should look something like this although this does not appear to be a jquery object when I am debugging (I could be wrong).

What is the correct way this should be done?

$('.leg-number').each(function () {
        this.html('foo');
    });
Share Improve this question asked May 24, 2013 at 1:15 ojhawkinsojhawkins 3,28816 gold badges53 silver badges69 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

Maybe try this instead:

$('.leg-number').html('foo');

which is a shorter and more efficient way to achieve your goal. It is just asking jQuery to set the inner html of every element with class "leg-number" to "foo" without any explicit iteration. Most of the jQuery methods like .html() can work on sets of elements so you don't really need to use .each() for simple cases like this.

Now on why your version didn't work: Using .each() would work if you wrapped this with the jQuery function $() so you could use the jQuery methods on it:

$('.leg-number').each(function () {
    $(this).html('foo');
});

The variable this inside of the .each() callback is a DOM element and you need $(this) to convert it into a jQuery object that wraps this element. See the explanation in the answer by epascarello who explained it before I updated my answer.

Read the docs for each(). this is a DOM Html Element node, not a jQuery object reference. You can either convert it back to jQuery or use innerHTML directly.

$(this).html('foo');

or

this.innerHTML = 'foo';

The docs show using $(this) in the examples.

Change:

this.html('foo');

to:

$(this).html('foo');

You're attempting to use a jQuery method on a non-jQuery object. This of course assumes that your table cells have the class .leg-number.

发布评论

评论列表(0)

  1. 暂无评论