最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JQuery - Javascript - .hasData() not working for me - Stack Overflow

programmeradmin0浏览0评论

I am trying to check if an object with class sourceFocus has data in it. However when I check it, it does not have data when it should. What am I doing wrong here?

$('.source').click(function() {
    $('.source').removeClass('sourceFocus'); 
    $(this).addClass('sourceFocus'); 
    $(this).data('source_selected', true);
    console.log($.hasData(this));
    console.log(this);
});

$('.target').click(function() {

    $('.target').removeClass('targetFocus'); 
    $(this).addClass('targetFocus'); 

    $(this).data('target_used', true);
    //$('.sourceFocus').data('source_used', true);

    console.log($.hasData('.sourceFocus'));

    if($.hasData('.sourceFocus')){
        console.log("has data worked");
        check_for_duplicates();
}

I am trying to check if an object with class sourceFocus has data in it. However when I check it, it does not have data when it should. What am I doing wrong here?

$('.source').click(function() {
    $('.source').removeClass('sourceFocus'); 
    $(this).addClass('sourceFocus'); 
    $(this).data('source_selected', true);
    console.log($.hasData(this));
    console.log(this);
});

$('.target').click(function() {

    $('.target').removeClass('targetFocus'); 
    $(this).addClass('targetFocus'); 

    $(this).data('target_used', true);
    //$('.sourceFocus').data('source_used', true);

    console.log($.hasData('.sourceFocus'));

    if($.hasData('.sourceFocus')){
        console.log("has data worked");
        check_for_duplicates();
}
Share Improve this question asked Aug 23, 2011 at 18:14 RATaboraRATabora 3935 silver badges10 bronze badges 2
  • Can you paste the HTML also, want to know see where you assigning the class sourceFocus and do you want read the HTML between the tags for which you using the sourceFocus class – Safran Ali Commented Aug 23, 2011 at 18:33
  • You can also check if the returned data value is undefined $obj.data('hello') !== undefined – KyleMit Commented Nov 28, 2017 at 14:49
Add a ment  | 

3 Answers 3

Reset to default 3

I don't think the .hasData() method accepts selectors in your case .sourceFocus, try selecting .sourcefocus as an element and then passing that to the .hasData() function.

try something like...

console.log($.hasData($('.sourceFocus:first')));

$.hasData() checks against a DOM Element you have to get it out of the jQuery object, either using array notation or the .get() method (not to be confused with the $.get() ajax method)

console.log($.hasData($('.sourceFocus')[0]));

If you trying to read the HTML between the tags for which you are using .sourceFocus class then do this in your if statement:

$.hasData($('.sourceFocus').html())
发布评论

评论列表(0)

  1. 暂无评论