简体   繁体   English

jQuery数据属性选择器未定义

[英]JQuery data attribute selector undefined

I'm having trouble with data attributes in some basic html and javascript. 我在一些基本的html和javascript中遇到了数据属性的问题。 I have several links throughout a page that dynamically insert a map and a 'close' link to get rid of the map. 我在整个页面中有几个链接,这些链接可动态插入地图,并提供“关闭”链接以摆脱地图。

The links are all similar to: 链接都类似于:

<a class="maplocation" href="#" data-coords="4645/234234" data-zoom="9">Link text<span class="mapslideicon"></span></a>

And the javascript on clicking these links is: 点击这些链接的javascript是:

$("a.maplocation").click(function() {
    if ($(this).data("mapopen") == true) {
        // Map already clicked and open, do nothing
    } else {
        var timeStamp = $.now();
        var mapID = "m_"+timeStamp;
        var mapCloseID = "c_"+timeStamp;
        var anchorID = "a_"+timeStamp;
        var mapClass = 'widemap';
        var mapDiv = $("<div class='"+mapClass+"' id='"+mapID+"'>&nbsp;</div><a href='#' id='"+mapCloseID+"' class='maplocationclose'>close</a>");
            mapDiv.insertAfter($(this).parent());
        // Set a data attribute on the link to let it know a map is open
        $(this).data( "mapopen", true );
        // Set a data attribute on the link so that we can reference it from the close button
        $(this).data( "anchorid", anchorID );
    }
    return false;
});

This creates a div for a map, places a data attribute on the original anchor to say that the map is open and also creates an anchor for closing the map. 这将为地图创建一个div,在原始锚点上放置一个数据属性以表示该地图已打开,并且还创建了一个用于关闭地图的锚点。

When the close map anchor is clicked it executes the following: 单击关闭地图锚点后,它将执行以下操作:

$('body').on('click', 'a.maplocationclose', function(){ // delegated.
        var id = $(this).attr('id');
        idNo = id.split("_");
        var assocMapID = "m_"+idNo[1];
        var assocAnchorID = "a_"+idNo[1];
        $("#"+id).remove();
        $("#"+assocMapID).slideUp( 300, function() {
            $("#"+assocMapID).remove();
        });
    // Set a data elemt on the original map link that let's us know the map is closed again
    $('.maplocation[anchorid="'+assocAnchorID+'"]').data( "mapopen", false );
    return false;
});

This all works but I'm having difficulty in accessing the data-attribute from the close anchor. 所有这些都可以,但是我很难从紧密锚点访问数据属性。 It references fine from the original link, as I intended, and sets the mapped attribute as true and reads it as true. 如我所愿,它从原始链接中引用了fine,并将映射的属性设置为true并将其读取为true。 However, when I set it to false in the close anchor it cannot find it and it's never set. 但是,当我在紧密锚点中将其设置为false时,找不到它,并且从未设置过。

I've run a test (from inside the maplocationclose function) to see if I can find any data attributes from the anchor, such as: 我已经运行了一个测试(从maplocationclose函数内部),以查看是否可以从锚点找到任何数据属性,例如:

console.log("Zoom Attr is: " + $('a.maplocation[anchorid="'+assocAnchorID+'"]').data('zoom'));

And they're returning 'undefined'. 他们正在返回“未定义”。

Attaching data using .data() does not add/alter any data-* attributes, hence your attribute selector won't match anything. 使用.data()附加数据不会添加/更改任何data-*属性,因此属性选择器不匹配任何内容。

You can use filter instead though: 您可以改用filter:

$('.maplocation').filter(function(){
    return $(this).data('anchorid') == assocAnchorID;
}).data( "mapopen", false );

Just to expand on the comments following @Georges answer. 只是为了扩展@Georges回答之后的评论。

Your code that is causing issues: 您的导致问题的代码:

$('.maplocation[anchorid="'+assocAnchorID+'"]').data( "mapopen", false );

Now, first of all the syntax for this selector is wrong. 现在,此选择器的语法首先是错误的。 Even if you have a data attribute named anchorid on an element, that is not how you would retrieve it. 即使您在元素上具有名为anchorid的数据属性,也无法以这种方式检索它。 You should include the data- part; 您应该包括数据部分; data-anchorid . data-anchorid

Check the below example, and the console output, to understand why it is failing: 检查以下示例以及控制台输出,以了解失败原因:

<div class="maplocation" data-anchorid="25" data-test="works">...</div>  

var x = $('.maplocation[anchorid="25"]');
var y = $('.maplocation[data-anchorid="25"]');
console.log('Length of x: ' + x.length) //This is 0, because element x does not exist
console.log('Length of y: ' + y.length) //1
console.log('Value of x: ' + x.data('test')) //This is undefined because element x does not exist
console.log('Value of y: ' + y.data('test')) //works

But, that doesn't solve the issue, since you have no attribute on the actual element you can't use that selector either. 但是,这不能解决问题,因为您在实际元素上没有属性,因此也不能使用该选择器。 data() is not writing to the element, like attr() does, but instead it only adds the keys/values to the jQuery internal collection/cache. data()不会像attr()那样写入元素,而是仅将键/值添加到jQuery内部集合/缓存。

jQuery docs on data() : 关于data() jQuery文档:

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements. 存储与匹配的元素关联的任意数据,或在匹配的元素集中的第一个元素的命名数据存储中返回值。

jQuery docs on attr() : attr()上的jQuery文档:

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element. 获取匹配元素集中第一个元素的属性值,或者为每个匹配元素设置一个或多个属性。

See this for an illustration: 参见以下插图:

$('.maplocation').data('mydata','myvalue'); //Only added to jQuery collection/internal cache, not DOM/element
console.log($('.maplocation[data-mydata="myvalue"]').data('test')) //undefined
$('.maplocation').attr('data-mydata','myvalue'); //Added to DOM/element
console.log($('.maplocation[data-mydata="myvalue"]').attr('data-test')) //works

Solutions 解决方案
So, the solution provided by George will work since it will get a collection of all elements with .maplocation and then filter that to only return the one that has a .data('anchorid') == assocAnchorID . 因此,乔治提供的解决方案将起作用,因为它将获得所有具有.maplocation元素的.maplocation ,然后对其进行过滤以仅返回具有.data('anchorid') == assocAnchorID

Other options: 其他选项:

  • You can use attr() instead of data() for setting/getting. 您可以使用attr()代替data()进行设置/获取。 Everything will be treated as strings, so you'll have to modify the code accordingly, and remember to include 'data-' when using it (example: data('test') should be attr('data-test') ). 一切都将被视为字符串,因此您必须相应地修改代码,并记住在使用时包括'data-' (例如: data('test')应该为attr('data-test') )。 Example: 例:

     $('.maplocation[data-anchorid="'+assocAnchorID+'"]').attr( "data-mapopen", "false" ); 
  • You can use another selector to get the element, then use data() as normal. 您可以使用另一个选择器来获取元素,然后照常使用data() This is just an example as I don't know if closest will work with your structure: 这只是一个示例,因为我不知道closest的结构是否适合您的结构:

     $(this).closest('.maplocation').data( "mapopen", false ); 

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

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