attr() not working in IE

2019-07-15 11:09发布

问题:

after browsing some similar question on here I couldn't find anything to help me fix my problem. In Chrome it works, get to IE and I get "aN,AN,NAN"

the HTML

<div class="dateSelect">
  <div class="prev">
      <a class="prevMonth" name="05,27,2013">month</a>
  </div>
</div>

the jQuery

$(".dateSelect a").click(function(event){
        var dateParam = $(this).attr('name');

        alert("link was clicked and value of NAME is: "+dateParam);
        dateChange(dateParam);
        event = event || window.event;
        event.stopPropagation();
    });

In Chrome it grabs the date "05,27,2013" but IE it's "aN,aN,NaN" I have a sneaky suspicion IE doesn't like attr(). If that's the case, is there an alternative way? Thank you in advance!

回答1:

name has the same rules as id, can't start with a number and no special chars, and IE hates it...

in this case, use data- attributes, like:

<a class="prevMonth" data-name="05,27,2013">month</a>

and from your script get it through:

$(this).attr("data-name") or $(this).data("name").

it even works with IE6 (if you still using version 1.x of jQuery) :)