简体   繁体   中英

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:

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


I have the following function creating a dynamic 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".

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.

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 .

If you initially had a data attribute on an HTML element, then doing $('foo').data('bar') would cause jQuery reading the attribute into memory. Further working with that data , modifying it, will not cause the attribute to change.

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.

To explicitly update the HTML attribute, use this:

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

But it's slower and converts the value into a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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