jQuery在控制台中工作但不是在原始代码中工作

Mid*_*hew 11 jquery

我尝试了以下代码将href添加到td中的a标记.我在控制台做的很好.但是当我在我的代码中尝试相同时它不起作用.谁能告诉我原因?

<script>
    $("table tbody tr td a").attr('href','http://www.google.com');
 </script>
<table>
    <tr>
        <td><a >Hai</a></td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

Gui*_*tos 14

使用document.Ready()

$(document).ready(function() {
    $("table tbody tr td a").attr('href','http://www.google.com');
});
Run Code Online (Sandbox Code Playgroud)

在尝试操作DOM之前,您需要确保已加载文档.

更多信息:http://api.jquery.com/ready/

  • 那么......给他答案吗? (4认同)

Jer*_*ant 7

执行jquery时,该元素不存在.您需要将处理程序放在准备好的函数中.

<script type="text/javascript">
$(function() {
    $("table tbody tr td a").attr('href','http://www.google.com');
});
</script>
Run Code Online (Sandbox Code Playgroud)

$(function() {}); 是简写 $(document).ready(function() {});


Ste*_*fan 6

JS在创建html之前触发.

<table>
    <tr>
        <td><a >Hai</a></td>
    </tr>
</table>
<script>
    $(function() {
        $("table tbody tr td a").attr('href','http://www.google.com');
    });
 </script>
Run Code Online (Sandbox Code Playgroud)


use*_*ser 4

把它放在准备好的部分:

<script type="text/javascript">
$(document).ready(function() {
 $("table tbody tr td a").attr('href','http://www.google.com');
});
</script>
Run Code Online (Sandbox Code Playgroud)