简体   繁体   中英

why data-attribute shows undefined while getting data value from HTML element using JQUERY

FIDDLE

I am trying to get the data attributes value of an HTML element it shows undefined object[] nothing goes work for me. Check my fiddle.

$(document).on("click", ".modal-open", function() {
    var $_target = $($(this).data("targetlocation"));
    var $_url = $($(this).data("targeturl"));
    console.log($_target);
    console.log($_url);
})

You need to use:

var $_target = $(this).attr("data-target-location");
var $_url = $(this).attr("data-target-url");

or

var $_target = $(this).data("target-location");
var $_url = $(this).data("target-url");

Working Demo

When using identifier with multiple words, You need to use camelCase notation

var $_target = $(this).data("targetLocation"); //Notice L 
var $_url = $(this).data("targetUrl");

DEMO

if you are going with this html Element

 <button type="button" class="modal-open" data-target-url="ajax.html" data-target-location=".overlay"> Modal open </button>

after triggering a click event on button "this" will return same html Element, therefore to fetch current data attribute value of this type.

You should use Camel Casing notation.

var $_target = $(this).data("targetLocation");
var $_url = $(this).data("targetUrl");

Working Example

    $(".modal-open").on("click", function() {

        var $_target = $(this).attr("data-target-location");
        var $_url = $(this).attr("data-target-url");
        alert($_target);
        alert($_url);
     });

Use this for Getting Attributes

Demo for this shows there Demo There

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