无法使用jquery的click事件追加div

时间:2015-09-01 09:30:10

标签: javascript jquery html

大家好我想动态地将div添加到我点击的div中。这是代码

fluent-ffmpeg

有谁能告诉我我的代码有什么问题

6 个答案:

答案 0 :(得分:3)

您的代码中存在3个问题

  1. 您不能拥有脚本标记的src和内容
  2. 由于您的脚本是在加载元素之前放置的,因此您需要将脚本放在dom ready处理程序中
  3. 你的html
  4. 中没有名为hello的类

    所以

    <div class="hello">Hello guys</div>
    <div class="hello">Hiiiiiiii</div>
    <div class="hello">Awesome</div>
    
    <script src="query.js"></script>
    <script>
        jQuery(function ($) {
            $('.hello').click(function () {
                $(this).append('<div>I am the new one</div>');
            });
        })
    </script>
    

答案 1 :(得分:2)

尝试将您的jquery代码包装在document.ready

$(document).ready(function(){ // this will execute when DOM is ready
  //your code 
  $('.hello1').click(function(){ //updated class name
    $(this).append('<div>I am the new one</div>');
  });
})
  

我可以看到你正在使用hello类绑定点击事件   不会出现在您的HTML中。所以如果你想把事件附加到所有人   以hello开头的课程使用此:

$(document).ready(function(){
    $('div[class^="hello"]').click(function(){
        $(this).append('<div>I am the new one</div>');
    }); 
});

DEMO

而不是这个

<script src="query.js"> //don't use src here

使用:

<script type="text/javascript">

答案 2 :(得分:2)

试试这个:你没有class="hello"的div,而是以hello hello1 hello2hello3$(document).ready(function...开头的类。因此,请使用选择器启动,如下所示。同时将您的代码放在$(function(){...<script src="query.js"></script> <script> $(function(){ $('div[class^="hello"]').click(function(){ $(this).append('<div>I am the new one</div>'); }); }); </script> 中,以确保DOM已准备好并附加Click事件处理程序。

首先必须包含jquery库,然后将jquery脚本放在另一个脚本标记中。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

答案 3 :(得分:2)

  1. 您需要在使用之前包含jQuery并使用它。使用

    <script src="query.js">$('.hello')...</script>
    
  2. 您无法加载脚本并在其中定义脚本。因此,以下无效

    ready()
  3. 使用DOMContentLoaded<body>事件或将脚本移至hello
  4. 的底部
  5. 标记中没有<script src="query.js"></script> <script> $(document).ready(function() { $('.hello').click(function() { $(this).append('<div>I am the new one</div>'); }); }); </script> 类的元素,但您要在其上绑定事件。
  6. 代码:

    $(document).ready(function() {
      $('.hello').click(function() {
        $(this).append('<div>I am the new one</div>');
      });
    });

    <强>演示

    &#13;
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <div class="hello">Hello guys</div>
    <div class="hello">Hiiiiiiii</div>
    <div class="hello">Awesome</div>
    &#13;
    {{1}}
    &#13;
    &#13;
    &#13;

答案 4 :(得分:0)

您的代码中没有.hello个类,您使用hello1hello2hello3作为类名,它们都应该只是hello。< / p>

答案 5 :(得分:0)

首先,为了使用$()选择器,您需要包含适当版本​​的jquery。然后,您需要选择一个元素:您有任何带有hello类的元素,而是拥有hello1,hello2和hello3。你可以删除这些数字,所以他们都会有一个hello类。最后,因为在执行js代码时这些元素不存在,所以需要将代码包装在文档就绪事件中,或者将其移动到html body标记的末尾。祝你好运!

相关问题