簡體   English   中英

如何在jQuery對象上調用JavaScript方法

[英]How to call JavaScript methods on jQuery objects

讓我們直接說清楚。

不幸的是,以下代碼必須在IE8上運行。

應該找到與當前頁面的URL與nav中存在的<a>標記的href屬性匹配的URL。 然后,將該標記的類not-selected交換為selected或者默認將其轉換為第一個<a>標記。

的HTML

<ul id="nav">
    <li><a class="not-selected" href="index.php"><span>Index Page</span></a></li>
    <li>
        <a class="not-selected" href="page1.php"><span>Page 1</span></a>
    </li>
    <li>
        <a class="not-selected" href="page2.php"><span>Page 2</span></a>
    </li>
</ul>

JavaScript(jQuery)

var url = $(document).attr('URL');

var isIndexPage = true;

var menu = $('#nav').children('li');

var anchors = menu.find('a');

anchors.each(function(index) {

    //   Is the href the same as the page?
    if ($(this).href != null && anchor.href == url)
    {
        $(this).first().addClass('selected');
        if ($(this).className.match(/\bnot\-selected\b/))
        $(this).first().removeClass('not-selected');

        indexPage = false;
     }
     else
     {
         //   remove class="selected" if it has that class
         if ($(this).className.match(/\bselected\b/))
         {
             $(this).first().removeClass('selected');
         }
         //   Add class="trigger"
         $(this).first().addClass('not-selected');                    
      }
 });

 if (isIndexPage)
 {
     menu[0].childNodes[0].setAttribute('class', 'selected');
 }

在腳本上,我在調用className屬性(應為字符串)的match()函數的行上收到錯誤消息。

這是為什么?

如何使用可在IE8上使用的jQuery或JavaScript修復它?

先感謝您。

className是HTML元素的本機屬性,而您試圖將其作為jQuery對象的屬性來調用。 執行以下任一操作:

$(this)[0].className

要么

$(this).attr('class')

旁注:您不是首先要檢查元素是否具有類,而是假設它具有類。 如果元素沒有class屬性,則第二種(jQuery)方法將出錯,因為如果沒有class屬性,它將返回null (與本機className屬性相反,它在沒有相應class屬性的情況下默認為空字符串)。

你可以更換線

if ($(this).className.match(/\bselected\b/))

有了這個

if ($(this).hasClass('selected'));

這要簡單得多。 對於“未選中”類也是如此。

jQuery對象沒有className屬性,可以使用hasClass方法檢查元素是否具有類:

if ($(this).hasClass('not-selected'))

但是,您根本不需要該檢查。 您可以只刪除該類,並且如果該類不存在,則該調用將不執行任何操作。 您可以這樣做:

$(this).addClass('selected').removeClass('not-selected');

同樣,在else塊中,您無需檢查,只需刪除並添加:

$(this).removeClass('selected').addClass('not-selected');

實際上,您甚至不需要if ,您可以使用toggleClass和一個布爾值來實現。 這將是您的整個循環:

anchors.each(function() {
  var sel = $(this).href != null && $(this).href == url;
  $(this).toggleClass('selected', sel).toggleClass('not-selected', !sel);
});

另外,您在使用未定義的變量anchor時應使用$(this) 更改此行:

if ($(this).href != null && anchor.href == url)

至:

if ($(this).href != null && $(this).href == url)

我認為您應該對網址使用普通的JS,對於其余示例,請使用jQuery:

的JavaScript

var path = window.location.pathname;

$.each($('#nav li a'), function(index, anchor) {
    if(path.indexOf($(anchor).attr('href')) != -1) {
        $('#nav li a').removeClass('selected');
        $(anchor).addClass('selected').removeClass('not-selected');
    }
});

這是一個示例: http : //jsfiddle.net/2rSqL/

暫無
暫無

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

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