在单击按钮时添加DIV,但是添加的DIV响应不一样



我正在执行单击DIV的按钮,但问题是,它的执行方式与Main Div的执行方式不像调整&拖放。请帮助?

 <html>
    <head>
    <link rel="stylesheet" href="test.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script>
    $(function () {
     $("#box").resizable({
    alsoResize:"#main",
    alsoResize:"#title_bar",
    alsoResize:"#container"
    });
    $('#main').draggable();
           $("#button").click(function () {
                if ($(this).html() == "-") {
                    $(this).html("+");
                    } else {
                    $(this).html("-");
                }
                $("#box").slideToggle();
            }); 
    $("#NewWidget").click(function() {
             $("#container").append('<div class="main" id="main"><div id="title_bar" ><div id="button">-</div></div><div id="box"><div><h4>Hi user</h4><p>Hello Users. How are YOU?</p> </div></div>');
     });
    });</script>
    </head>
    <body>
     <input type="button" id="NewWidget" value="Add New Widget"/>
    <div id="container">
    <div class="main" id="main"  > 
            <div id="title_bar" >
            <div id="button">-</div>
        </div>
        <div id="box">
    <div>

ID的需要是唯一的,因此,如果创建了很多元素,则可以使ID的唯一或使用类别或data-id属性识别哪个框,在Codepen i中的示例中向您展示了如何使用简单的counter变量创建ID,该范围可在此范围中可用(请记住有关关闭(。

您在代码中所做的仅是appending dom的新结构,没有事件处理程序/钩子附加到此元素上的原因,这就是为什么您要么需要在将元素添加到DOM,或之后,在我的示例中,我会在将元素添加到DOM之前。

此处指向Codepen:https://codepen.io/anon/pen/geypxr

附加提示:只要可能

 $(".main").find('.button').on('click',function(){
   // this looks weak, plus anonymous function doesn't tell you what it does
});

而是使用此:

$(".main").find('.button').on('click',makeButtonWork);
function makeButtonWork(){
  //this looks much better, plus you named the function and you know the purspose of it, without looking through code
}

回答评论:可以通过添加以下方式更改给定元素的起始位置:

$('#main-' + counter).css({'top': 100, 'left' : 20}) //your positions heremakeButtonWork

有关更多信息,请参见更新的Codepen

javaScript事件不起作用。将其作为拨打$('#main').draggable();的那一刻,然后浏览器找到匹配元素(此处具有ID" main'"(并对其进行了一些操作(此处启用可拖动功能(。如果您以后添加另一个元素(也将匹配(,那并不意味着任何内容 - 它只是一个普通的DIV,直到您再次调用一些脚本为止。

另外,请记住,ID在您的页面上必须是唯一的,您不能在同一页面上具有两个ID =" Main" Divs。改用类。

$("#NewWidget").click(function() {
    var $newElement = $('<div class="main"><div class="title_bar" ><div class="button">-</div></div><div class="box"><div><h4>Hi user</h4><p>Hello Users. How are YOU?</p> </div></div>');
    $newElement.find('.main').draggable();
    $newElement.find('.button').click(  /* add the click handler function here */ );
    $newElement.find('.box').resizable( /* resizable params goes here */ );
    $("#container").append($newElement);
});

最新更新