简体   繁体   中英

How can I set the title on an element from an attribute of the element?

I am using the following code:

    $(targetSelector)
        .attr({
            'data-disabled': 'yes',
            'data-title': function() { return this.title },
            'title': ''
        })
        .addClass('disabled')
        .prop('disabled', true);

This sets the element's title to '' after first having stored it in data-title.

How can I restore the elements title by getting it back from the data-title attribute if the title is currently equal to the empty string? I assume I need to do this in a function like the above but how can I code in a check into the function?

Everything you atore in a data-* attribute is accessible from jQuerys data(name) method where name is what follows data- so you can use the below code

$(targetSelector)
    .attr('title',function() { return this.title || $(this).data("title"); })

This will also set the title if the attribute title is not present or if this.title returns any other falsy value (eg false ) however I'm assuming that you wish to set the value in both the cases where this.title === "" and this.title === undefined and that the latter is not expected (which would require that the title attribute at some point was set explicitly to the boolean value false

You can try this:

$(targetSelector).attr('title', function() {
    return this.title || $(this).data('title');
});

If will return the title if it is falsy , else it will grab the data-title attribute.

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