jQuery attr in IE7

时光怂恿深爱的人放手 提交于 2019-12-12 06:13:20

问题


I have the following HTML:

<a href="myPage.htm">
  <img src="anImage.jpg />
</a>
<a href="yourPage.htm">
  <img src="anotherImage.jpg />
</a>
<a href="everyonesPage.htm">
  <img src="stillAnotherImage.jpg />
</a>

And the following javascript (using jQuery):

$(document).ready(function(){
  $('a').live('click', function(e){
    e.preventDefault();
    alert($('img', this).attr('src'));
  });
});

In Firefox this alerts the src attribute of the image clicked, but in IE7 and IE6 it alerts 'undefined'. Any ideas why this is and how to return the src of the image when clicking the relevant anchor tag?

EDIT: Sorry guys, jsFiddle example here (http://jsfiddle.net/wabqw/) with original code (yes, code above was a simplified version). Works in Chrome but no IE (firefox fails to display the images so there's nothing to click on!).


回答1:


I suspect there might be a problem with your HTML, as you are missing quotes:

<img src="anImage.jpg />

Should be

<img src="anImage.jpg" />

Different browsers may handle this in different ways

For me, in Chorme, it certainly doesn't work in this JSFiddle: http://jsfiddle.net/apKdC/, however when I fix the quotes in this updated fiddle: http://jsfiddle.net/apKdC/1/ it all works fine.




回答2:


The real problem is that before version 9, Internet Explorer does not recognise unknown elements, such as the HTML5 elements you're using.

You can fix it by including this in your <head>:

<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

For some background information, read: http://paulirish.com/2011/the-history-of-the-html5-shiv/

Here's a page that does just that, and works in IE6/7: http://jsbin.com/izina3




回答3:


you don't have correct html syntax see src attribute in first image missing " http://jsfiddle.net/HwmEK/1/ see here its working




回答4:


I could be totally off-track here but shouldn't you have:

alert($('img', $(this)).attr('src'));

So $(this) not this



来源:https://stackoverflow.com/questions/6200087/jquery-attr-in-ie7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!