JQuery Style不适用于通过Javascript加载的表

时间:2017-08-23 16:48:26

标签: javascript html

我正在尝试选择包含特定文本字符串的任何元素,并将其背景颜色设置为黄色。在我的示例中,javascript影响HTML表,但似乎不影响通过Javascript加载的表。我已经尝试将脚本放在最后/使脚本运行最后但我似乎无法绕过这个。

小提琴:http://jsfiddle.net/p2yLcsw0/47/

<html>
    <body>

    <div class="sheetstotables"></div>
    <script type="text/javascript">
    var tableId = "9OD4Y"
    var x = document.createElement("script"); x.type = "text/javascript"; x.async = true;
    x.src = "http://www.sheetstotables.com/get_table.js";
    var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(x, s);
    </script>

    <table>
      <tr>
        <th>cy</th>
        <th>cy</th>
        <th>Country</th>
      </tr>
      <tr>
        <td>Alfreds Futterkiste</td>
        <td>Maria Anders</td>
        <td>Germany</td>
      </tr>
      <tr>
        <td>Centro comercial Moctezuma</td>
        <td>Francisco Chang</td>
        <td>Mexico</td>
      </tr>
      <tr>
        <td>Ernst Handel</td>
        <td>Roland Mendel</td>
        <td>GK</td>
      </tr>
      </table>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(".windowbg td:contains(GK)").css("background-color", "yellow");
    });
    </script>

    </body>

    </html>

2 个答案:

答案 0 :(得分:1)

问题是你的脚本在加载表之前执行解决方案是让你的脚本等待你的表加载这个使用setTimeout函数,如下所示:

$(document).ready(function(){
    setTimeout(function() {
 $("td:contains(GK)").css("background-color", "yellow");
}, 3000)

});

答案 1 :(得分:1)

这是因为你的http://www.sheetstotables.com/get_table.js执行异步任务,如果你编码:

$(document).ready(function(){
    $("td:contains(GK)").css("background-color", "yellow");
    console.log($("td:contains(GK)").length) //It will print 1
    setTimeout(function(){
        console.log($("td:contains(GK)").length) //It will print 10
    },1000)
});

你可以在你的&#34; xmlhttp.onreadystatechange&#34;中编码。功能,它将工作

$("td:contains(GK)").css("background-color", "yellow");