简体   繁体   English

在jquery .html()附加后,绑定不起作用

[英]Bindings are not working after jquery .html() append

I have this simple div: 我有这个简单的div:

<div id="mainContent">

</div>

and it's empty. 它是空的。 Now I'm trying to append this HTML to the above div: 现在我正在尝试将此HTML附加到上面的div:

<div id="mainContent">
   <label>Project Name</label>
   <input type="text" id="projectName" data-bind="value: projectName"/> 
   <label>Tracker Name</label>
   <input type="text" id="trackerName" data-bind="value: trackerName"/>
</div>
<button type="submit" data-bind="click: submitNewProject">Submit</button>

By using: 通过使用:

                       $.ajax({
                             type : 'POST',
                             url : 'newTracker.php',
                             dataType : 'html',
                             success : function(data){
                                     $("#mainContent").html(data);
                             },
                             error : function(XMLHttpRequest, textStatus, errorThrown) {
                                     alert('Something is wrong!');
                             }
                     });

Where data is the HTML I'm trying to assign by: $("#mainContent").html(data); data是我试图分配的HTML$("#mainContent").html(data);

At first look everything looks pretty, but there is a problem - the bindings are not working. 起初看起来一切都很漂亮,但是有一个问题 - 绑定不起作用。

What I mean is that in the newly assigned HTML I have a button supposed to call a viewmodel function, but it does not... 我的意思是在新分配的HTML我有一个按钮应该调用一个viewmodel函数,但它不...

BUT if I place the code directly inside of the div the bindings are working like a charm. 但是,如果我将代码直接放在div中,绑定就像魅力一样。

Why my bidings are not working when I'm assigning a new HTML code inside of the div? 当我在div中分配新的HTML代码时,为什么我的出价不起作用? I know that I'm missing something really small and basic here, but I can't spot it. 我知道我错过了一些非常小而基本的东西,但我无法发现它。

EDIT: 编辑:

Button event: 按钮事件:

 submitNewProject = function(){
                            console.log("submit new project");
                        };

Knockout cannot track newly created elements, if your DOM changed using Ajax methods you'll have to explicitly bind a view-model to the newly created elements. Knockout无法跟踪新创建的元素,如果使用Ajax方法更改DOM,则必须将视图模型显式绑定到新创建的元素。

Something like: 就像是:

$.ajax({
    type: 'POST',
    url: 'newTracker.php',
    dataType: 'html',
    success: function (data) {
        var $mainContent = $("#mainContent");
        $mainContent.html(data);

        var existingViewModel = ko.dataFor(document.body);
        ko.applyBindings(existingViewModel, $mainContent.get(0));
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('Something is wrong!');
    }
});

Sometimes you need to create a secondary function on the parent page to apply the bindings and then call that function from within the appended text. 有时您需要在父页面上创建辅助函数以应用绑定,然后在附加文本中调用该函数。 All the functions defined on the original page as it loads will be available. 在加载时在原始页面上定义的所有功能都将可用。 I have used this method before, though you have to know in advance what functions you will need to build. 我以前使用过这种方法,但你必须事先知道需要构建哪些函数。 Or you can just include the binding as part of the post-ajax process. 或者您可以将绑定包含在post-ajax进程中。

It makes ajax loads with decent functionality 它使ajax加载具有不错的功能

function bindStuff() {
    $(".class1").click(function() {
        // do something with the bind        
    });
}
function ajaxLoad() {
    // Perform ajax load
    // on complete call your bindings
    complete: function() {
        bindStuff();
    }
}

With your example: 用你的例子:

                  $.ajax({
                         type : 'POST',
                         url : 'newTracker.php',
                         dataType : 'html',
                         success : function(data){
                                 $("#mainContent").html(data);
                         },
                         complete: function(){
                                 bindStuff();
                         },
                         error : function(XMLHttpRequest, textStatus, errorThrown) {
                                 alert('Something is wrong!');
                         }
                 });

As most have pointed out. 正如大多数人所指出的那样 When you add the HTML dynamically with the append, the DOM isn't reevaluating the bindings. 使用append动态添加HTML时,DOM不会重新评估绑定。 So, you need to either: 所以,你需要:

  1. apply/reapply your bindings in the .ajax success event handler .ajax success事件处理程序中应用/重新应用绑定
  2. apply/reapply your bindings in a document html onChange handler document html onChange处理程序中应用/重新应用绑定
  3. place your HTML statically in the first place but use a class for all the elements that has a style of set the display:none , then change the style to display:block , display:inline-block , etc.. 首先静态放置HTML,但对所有具有设置display:none样式的元素使用 ,然后将样式更改为display:blockdisplay:inline-block等。
  4. use a hybrid of above with some static HTML to at least establish the binding between the button and function and anything else that will be required to make the bindings work, but then dynamically .append() anything else that is not dependent on the binding 使用上面的混合与一些静态HTML来至少建立按钮函数之间的绑定以及使绑定工作所需的任何其他东西,然后动态地.append()任何其他不依赖于绑定的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM