简体   繁体   中英

JQuery: Assigning value to td span if span is empty

I have a table with functions connected to a database. If the player score exists, the value is assigned to the td span. If there is no player score, no value is assigned to the td span. I'm trying to populate the span with "0" if a score doesn't exist, or if the td span is empty.

$("table tbody tr").children('td').find("span.playerScore").each(function () {
    var test = $(this).text();
    if (test === "") {
        $(this).parent("td").children('span').text() = "0";
    }
})

This isn't working. I definitely feel it's something obvious and I'm just blind so any help is appreciated. Thanks.

This...

$(this).parent("td").children('span').text() = "0";

is not how you set the text of an element.

You need to pass the text as an argument to text :

$(this).parent("td").children('span').text("0");

It might be easier to use the :empty selector. That can save a couple lines of code.

It's important to note that the value of the text has to be enclosed inside parenthesis.

$("table tbody tr").children('td').find("span.playerScore").filter(":empty").each(function () {
    $(this).parent("td").children('span').text("0");
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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