jQuery .data() does not update HTML5 data attributes

霸气de小男生 提交于 2019-12-04 04:17:04

问题


I am trying to add a "data-bind" attribute to a div using jQuery as follows:

var messageViewModel = {
    data: ko.observable({   
        message: response.message, 
        sendDateFmted: response.sendDateFmted, 
        messageId: response.messageId
    })
     };

$("<div>",{
    class:"messageToAndFromOtherMember"
}).data("bind", "template: { name: 'message-template', data: data }").appendTo("#messagesToAndFromOtherMember");

ko.applyBindings(messageViewModel);

"data-bind" is required by KnockoutJs. However all I get is this empty div:

<div class="messageToAndFromOtherMember"></div>

Notice there is no such attribute as data-bind and therefore the div remains empty...


回答1:


jQuery's .data() stores the values in-memory and uses data-* attributes for initialization. You may want to stick by setting it at element creation.

$("<div/>", {
  class: "messageToAndFromOtherMember",
  "data-bind": "template: { name: 'message-template', data: data }"
}).appendTo("#messageToAndFromOtherMember");



回答2:


Alexander's answer is definitely correct, in the general sense, but I couldn't help but notice that in your specific example you seem to be adding messages to your code by creating a new binding scope for each message. If this is the case, I think you are using Knockout incorrectly (if not, let me know and I will just remove this).

If you are getting new messages from a server, and just trying to display the list of them on the page, a much better structure would be to use an ObservableArray, and simply push new messages to it. The standard knockout binding will automatically add the new messages to your html, without the mess of creating a new binding scope, and a completely independent viewmodel for the new message. You can see this in action in this fiddle.

Here is the rather contrived ViewModel:

var ViewModel = function(data) {
    var self = this;
    self.messages = ko.observableArray();
    self.newMessage = ko.observable('');
    self.addMessage = function() {
        var message = new Message({ message: self.newMessage()});
        self.newMessage('');
        self.messages.push(message);
    };
};


来源:https://stackoverflow.com/questions/13673369/jquery-data-does-not-update-html5-data-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!