简体   繁体   English

为什么单击鼠标后看不到动态创建的按钮上的数据字段?

[英]Why can't I see the data-field on a dynamically created button when clicked?

Edit: Here is a JSFiddle which displays the problem I'm having: 编辑:这是一个JSFiddle,它显示了我遇到的问题:

http://jsfiddle.net/gyhvpmgy/4/ http://jsfiddle.net/gyhvpmgy/4/


I have the following function creating a dynamic div: 我有以下创建动态div的功能:

InvalidField.prototype.getMessageStructure = function(){
    var div = $('<div></div>').addClass('invalidRow');      
    var span = $('<span></span>')
        .text(this._message)
    var button = $('<button></button>')
        .addClass('btn_AlertFocus')
        .text("Go To Field")
        .data("field", this._field[0].name)    

    return div.append(button).append(span);
};

Prior to the return line, through debugging I can see that button.data('field') contains, as it should: "applicant.email". 在返回行之前,通过调试,我可以看到button.data('field')包含,因为它应该是:“ applicant.email”。

I also have the following generic button click event: 我还具有以下通用按钮单击事件:

$(document).on('click', '.btn_AlertFocus', function() {
    var field = $(this).data('field');
    goToFieldFromAlert('input[name="' + field + '"]');
});

'field' is now coming up as undefined. 现在,“字段”出现为undefined。

Is anyone able to tell me why, it will probably be something obvious - this is a new feature to me? 有谁能告诉我为什么,这可能很明显-这是我的新功能?

Below is the snippet that takes this returned string value. 以下是采用此返回的字符串值的代码段。

function validateForm(){
    if(list_Invalid.size() > 0){
        var structure = "";
        for ( i = 0; i < list_Invalid.size(); i ++){
            structure += list_Invalid.item(i).getMessageStructure()[0].outerHTML;
        }
        var alert = new Alert(structure, 
                function(){
                }
            ).showAlert();      
        return false;
    }
    return true;
}

Many thanks! 非常感谢!

jQuery uses an internal representation for working with data . jQuery使用内部表示来处理data

If you initially had a data attribute on an HTML element, then doing $('foo').data('bar') would cause jQuery reading the attribute into memory. 如果您最初在HTML元素上具有data属性,则执行$('foo').data('bar')会导致jQuery将属性读入内存。 Further working with that data , modifying it, will not cause the attribute to change. 进一步使用该data ,对其进行修改,不会导致该属性发生更改。

If you didn't have the attribute in the first place, then jQuery would work with data in memory, and the attribute will never appear in HTML. 如果您首先没有该属性,则jQuery将使用内存中的data ,并且该属性将永远不会出现在HTML中。

To explicitly update the HTML attribute, use this: 要显式更新HTML属性,请使用以下命令:

$('foo').attr('data-bar', 'value');

But it's slower and converts the value into a string. 但这比较慢,并将值转换为字符串。

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

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