1

鉴于此表:

<table border="1" width="200" id="table1" cellspacing="0" cellpadding="0" style="border-collapse: collapse" bordercolor="#CB2F7F">
    <tr id="st_ppp">
        <td width="60%" class="totalLabels">Price per piece</td>
        <td width="39%" align="right" class="totalElements">unknown</td>
    </tr>
    <tr id="st_qty">
        <td width="60%" class="totalLabels">Quantity</td>
        <td width="39%" align="right" class="totalElements">unknown</td>
    </tr>
    <tr>
        <td width="60%">&nbsp;</td>
        <td width="39%" align="right">&nbsp;</td>
    </tr>
    <tr>
        <td width="60%" class="subTotalLabel">Sub-Total:</td>
        <td width="39%" align="right" class="subTotal">unknown</td>
    </tr>
</table>

我想做类似下面的伪代码:

document.getElementById("st_ppp").[td whose class is totalElements].innerHTML="NewPrice";
document.getElementById("st_qty").[td whose class is totalElements].innerHTML="NewQty";

我也愿意接受对 HTML 进行任何其他更改的建议,这些更改将使 JS 更易于使用。

4

2 回答 2

3

只需使用querySelectorMDN 链接)和相应的 CSS 选择器来获取您的元素并更改其内容。

document.querySelector( '#st_ppp .totalElements' ).innerHTML = "NewPrice";
document.querySelector( '#st_qty .totalElements' ).innerHTML = "NewQty";
于 2012-06-05T14:31:25.870 回答
2

如果您不担心与 Internet Explorer 7 及更早版本的兼容性,querySelector那么它是完美的(但如果您采用这种方式,则归功于 @Sirko):

document.querySelector('#st_ppp > .totalElements').innerHTML = "NewPrice";

如果您已经在使用 jQuery,那么它非常适合:

$('#st_ppp > .totalElements').text('NewPrice');

否则,循环将起作用:

var pricePerPiece = document.getElementById('st_ppp');
var i, c;

for(i = 0; c = pricePerPiece.children[i]; i++) {
    if((' ' + c.className + ' ').indexOf(' totalElements ') > -1) {
        c.innerHTML = 'NewPrice';
        break;
    }
}
于 2012-06-05T14:33:42.367 回答