jQuery working in console but not in original code

前端 未结 6 2525
南旧
南旧 2021-02-19 10:35

I have tried the following code to add href to the a tag inside a td. it is working fine while i do in console. But when I try the same in my code it is not working. Can anyone

相关标签:
6条回答
  • 2021-02-19 10:43

    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>
    
    0 讨论(0)
  • 2021-02-19 10:50

    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

    0 讨论(0)
  • 2021-02-19 10:52

    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/

    0 讨论(0)
  • 2021-02-19 10:53

    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>
    
    0 讨论(0)
  • The order of your jQuery files in the master layout page can also influence why it does not work in actual code but works in console of the browser. jQuery files must be referenced in the following order in the master page:

    <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>
    

    For people coming here looking for a solution to what it says in title without going into specifics of this particular question, hope it helps someone.

    0 讨论(0)
  • 2021-02-19 10:58

    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() {});

    0 讨论(0)
提交回复
热议问题