13

我尝试使用以下代码将 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>
4

7 回答 7

19

Use document.Ready()

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

You need to ensure that the document is already loaded before you try to manipulate the DOM.

More info: http://api.jquery.com/ready/

于 2013-07-15T17:33:52.760 回答
7

The element doesn't exist when your jquery is executing. You need to put your handlers inside a ready function.

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

$(function() {}); is the shorthand for $(document).ready(function() {});

于 2013-07-15T17:33:48.607 回答
6

The JS is firing before the html is created.

<table>
    <tr>
        <td><a >Hai</a></td>
    </tr>
</table>
<script>
    $(function() {
        $("table tbody tr td a").attr('href','http://www.google.com');
    });
 </script>
于 2013-07-15T17:34:17.523 回答
4

put it in a ready section :

<script type="text/javascript">
$(document).ready(function() {
 $("table tbody tr td a").attr('href','http://www.google.com');
});
</script>
于 2013-07-15T17:33:46.067 回答
4

Your code executes before the DOM is ready and the element actually exists, try it this way:

 <script>
    $(document).ready(function(){
      $("table tbody tr td a").attr('href','http://www.google.com');
    });
 </script>

The reason it works on console is because the <a> element already exists when you execute your code...

JSBin Demo

于 2013-07-15T17:34:09.460 回答
0

您的 jQuery 文件在主布局页面中的顺序也会影响为什么它在实际代码中不起作用但在浏览器的控制台中起作用。必须在母版页中按以下顺序引用 jQuery 文件:

<script type="text/javascript" src="/Scripts/jquery-3.1.1.min.js"></script>      
<script type="text/javascript" src="/Scripts/jquery-ui-1.12.1/jquery-ui.min.js"></script> 
<script type="text/javascript" src="/Scripts/bootstrap.min.js"></script>

对于来到这里寻找标题中所说内容的解决方案而不涉及这个特定问题的细节的人,希望它对某人有所帮助。

于 2019-06-24T15:07:13.993 回答
0

我有同样的问题,但上面的答案都没有解决它。我通过检查单击事件处理程序的存在来解决它,并设置一个我在弹出后清除的间隔

  <script type="text/javascript">
        var interval = setInterval(function() {
            if ( $(".content_btn").length) {
                $(".content_btn").click(function (){
                    var content = $(this).parent('div').children(".hidden_content").html();
                    var element = document.createElement('div');
                    element.innerHTML = `${content}`;
                    swal({
                        content: element,

                    });
                });
                clearInterval(interval);
            }
        }, 1000);
    </script>
于 2021-04-27T16:15:17.790 回答