2016-12-15 55 views
-1

我想要做的事情如:如果URL包含「type = department」做某事。jQuery - 索引不是函數

我有以下代碼:

var url = $(location).attr('href'); 
if(url.index("type=department") >= 0){ 
    do something 
} 

但我的控制檯寫信給我:遺漏的類型錯誤:url.index不是一個函數

有什麼不對?

+0

正確的方法是'indexOf()'。投票結束爲一個錯字。 –

+0

只是爲了完整性,因爲它可能是您混淆的根源; jQuery有一個['index'](https://api.jquery.com/index/)方法。 – Jamiec

回答

3

沒有功能index(),你需要String.prototype.indexOf()

if(url.indexOf("type=department") >= 0){ 
    //Do something 
} 

您還可以使用String.prototype.includes()

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

if(url.includes("type=department")){ 
    //Do something 
} 
+0

我有indexOf在那裏,它寫道,indexOf不是jQuery的函數。 –

+0

@MichalVlasák,'index()'是一個jQuery方法,其中'indexOf()'是本地字符串方法 – Satpal

0

我想你所說的網址你的意思是你的瀏覽器的URL。如果是這樣,那麼你應該做的是這樣的。

function getUrlParameter(sParam) { 
    var sPageURL = decodeURIComponent(window.location.search.substring(1)), 
     sURLVariables = sPageURL.split('&'), 
     sParameterName, 
     i; 

    for (i = 0; i < sURLVariables.length; i++) { 
     sParameterName = sURLVariables[i].split('='); 

     if (sParameterName[0] === sParam) { 
      return sParameterName[1] === undefined ? true : sParameterName[1]; 
     } 
    } 
} 

那麼你會做什麼與該功能低於...

可以說,您的網址爲http://www.example.com?type=department,你會做以下...

var type = getUrlParameter('department'); 
if(type!=undefined){ 
    do something here ... 
} 
0

有疑問時, look it up in the documentation

.attr(attributeName) Returns: String

而且由於返回類型是一個很好的老JavaSc ript字符串,而不是一個jQuery對象,你可以使用standard JavaScript documentation,我們可以看到沒有任何index()方法的痕跡。但是,我們看到幾種查找子字符串的方法,例如indexOf()

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() method.