簡體   English   中英

.attr('href') 返回未定義

[英].attr('href') returning undefined

我正在使用一個簡單的 JQuery 解決方案從鏈接中獲取 href 並將其應用於單擊事件。 這適用於 Webkit 和 Gecko 瀏覽器,但是 Internet Explorer (7 & 8) 一直將 href 位置顯示為undefined 有人對此有修復嗎? 可以幫我解決這個問題嗎? 如果是這樣,非常感謝。

 $('table tr').click(
    function () {
        var element = $(this).attr("class");
        var hrefLocation = $('#'+ element +' .deal-holder a').attr('href');
        alert(hrefLocation)
        window.location.href = hrefLocation;
        return false; 
    }
);

HTML 很簡單:

 <tr class="QRG">
    <td class="blue"><a href="#QRG">QRG</a></td>
    <td>Company Sale</td>
    <td>Technology</td>
 </tr>


 <div class="deal" id="QRG">
      <p><span class="js">Overview</span><span class="no-js">Enham</span></p>
      <div class="deal-holder">
         <div class="image-holder">
             <img src="../assets/images/enham.gif" alt="" height="70" width="150" />
         </div>
         <p>Enham is a charity established in 1918, which delivers a wide range of essential services that provide choice and empowerment to disabled people to make their own decisions about their lives. Enham is a charity established in 1918, which delivers a wide range of essential services that provide choice and empowerment to disabled people to make their own decisions about their lives</p>
         <a class="moreInfo" href="individual.html">More Information</a>
      </div>
 </div>

沒有什么讓我覺得錯了。

首先確保您使用的是最新版本的 jQuery,因為這有時會有所幫助。

我更改了您的代碼,因此tr中的鏈接具有點擊事件:

$('table tr a').click(function (e) {
    var element = $(this).closest('tr').attr("class"),
        hrefLocation = $('#'+ element +' .deal-holder a').attr('href');
    alert(hrefLocation)
    window.location.href = hrefLocation;
    e.preventDefault();
});

我在 這里 做了一個演示,它適用於 IE 7,8 和 9。希望這會有所幫助。

在不知道 html 代碼的 rest 的情況下,很難確切知道您的問題是什么,行為很大程度上取決於您的html的結構...但是它只使用了$(this)的指針:獲取子鏈接。

您可能需要 select 超鏈接組中的第一個元素。

$('table tr').click(
    function () {
        var element = $(this).attr("class");
        var hrefLocation = $('#'+ element +' .deal-holder a').eq(0).attr('href');
        alert(hrefLocation)
        window.location.href = hrefLocation;
        return false; 
    }
);

嘗試將其包裹在准備好的 function 中。
IE 可能正在嘗試將事件添加到 object 中,然后才進入 DOM:

$(document).ready(function(){

   $('table tr').click(
      function () {
         var element = $(this).attr("class");
         var hrefLocation = $('#'+ element +' .deal-holder a').attr('href');
         alert(hrefLocation);

         window.location.href = hrefLocation;
         return false; 
      });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM