0

我有一个<tr>有时在 two<td>的第一个中包含单词 Discount ,当它确实包含单词 discount 时,我希望为整个表行提供一个类,而当它不包含单词 discount 时我希望它保持无阶级。

似乎无法找出使用 javascript 执行此操作的正确方法。任何帮助将不胜感激。

4

5 回答 5

1

试试这个

// get all <tr>
var theTRs = document.getElementsByTagName('tr');
for(i=0; i<theTRs.length; i++) {
    // get first two <td>
    var theTDs = theTRs[i].getElementsByTagName('td');
    var theFirstTD = theTDs[0];
    var theSecondTD = theTDs[1];
    // check if one of those <td> contains "discount", if yes, add class
    if(theFirstTD.textContent.indexOf("discount") != -1 || theSecondTD.textContent.indexOf("discount") != -1) {
        theTRs[i].className = "yourclassgoeshere";
    }
}
于 2013-09-17T15:47:45.243 回答
0

要将脚本放在<script>标签中<head>,请按如下方式使用:

function styleRow() {
    var table = document.getElementById('shopping-cart-totals-table');
    var row = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (var i = 0; i < row.length; i++) {
        console.log('ok');
        if (row[i].getElementsByTagName('th').length > 0)
        {
            var inputTxt = row[i].getElementsByTagName('th')[0].textContent;
            if (inputTxt.toLowerCase().indexOf('discount') != -1) 
                row[i].className = 'red';
        }
    }
}
window.onload = styleRow;

工作演示

于 2013-09-17T15:49:10.570 回答
0

你可以试试这个

香草 JavaScript:

var tds = document.querySelectorAll('table tr td');
for(var i = 0; i < tds.length; i++)
{
    if(tds[i].innerHTML.toLowerCase() == "discount") {
        tds[i].parentNode.setAttribute('class', 'discount');
    }
}

演示。

jQuery:

$('table tr td:contains("Discount")').closest('tr').addClass('discount');

演示。

更新:

由于 jQuery:contains也匹配 word nodiscount,所以这是一个jQuery更好的解决方案的替代方案,IMO

$('table tr td').filter(function(){
    return (this.textContent || this.innerText).toLowerCase().match(/^discount$/);
}).parent('tr').addClass('discount');

演示。

于 2013-09-17T15:56:27.653 回答
0
$(document).ready(function(){
    $('table tr td')each(function(){
        if($(this).text().indexOf('Discount')>0)
            $(this).closest('tr').addClass('someClass');
    });
});
于 2013-09-17T16:01:12.903 回答
0

首先,您必须设置类css并添加您希望折扣行具有的样式。像这样的东西:

tr.discount-row {
    //your style here
}

然后代码:

var table = document.getElementById("MyDiscountTab"); //this is the table
var rows = table.getElementsByTagName("tr"); //these are the rows

for (var i = 0; i < rows.length; i++) { // do this for each row
    var col = rows[i].getElementsByTagName("td")[0]; //and this is the first column/cel of a row
    if (col.innerHTML.toLowerCase().indexOf("discount") > -1) {
        rows[i].setAttribute("class", "discount-row");// adding the class
    }
}

是的,这在窗口函数<script></script>内的标题中进行,如下所示:onload

window.onload = function() {
  //code here
};

或者可能是这样的:

myFunction = function () {
    //code here
}

...

window.onload = function() {
  myFunction();
};

这是一些您可以检查的演示。

于 2013-09-17T16:17:59.373 回答