2013-11-23 73 views

回答

1

我想你換貨真的檢查是否一些字符串包含給定的字符串。你可以做到以下幾點:

childValue.indexOf('color-'); 

如果子出現時,它會返回這個地方出現的子串,如果沒有它會返回-1的索引。

0

也許使用類似的東西?

$(selectChild).on('change',function(){ 
    var childOption = $("option:selected", this); 

    if (childOption.is('[value^=color]')) { 
     //show pickColor div 
    } else if (childOption.is('[value^=image]')) { 
      //show Upload div 
    } 

}); 

http://api.jquery.com/attribute-starts-with-selector/

0

開關你childValue和正則表達式

$(selectChild).on('change',function(){ 
    var childOption = $("option:selected", this), 
     childValue = this.value; 

    if(/color-/.test(childValue)){ 
     alert("color-"); 
     return; 
    } 
    if(/image-/.test(childValue)){ 
     alert("image-"); 
     return; 
    } 

}); 

http://codepen.io/anon/pen/FozGB

1

這個問題已經算不上什麼做用jQuery而是使用JavaScript本身。 「最乾淨」的方法是在JavaScript與startsWith-程序擴展字符串原型:

if (typeof String.prototype.startsWith != 'function') { 
    String.prototype.startsWith = function (str){ 
    return this.slice(0, str.length) == str; 
    }; 
} 

接下來,您可以使用新的程序與任何字符串你想要的:

if(childValue.startsWith ("color-")){ 
    //show pickColor div 
} 

你是否應該發現一個更好的方法來比較一個字符串的開始,你可以簡單地改變原型聲明一次。這比改變你在其他代碼中選擇使用的任何事情要容易得多。

來源:

Javascript StartsWith

+0

但是!現在我很困惑,'str.indexOf('color-')=== 0'完全一樣嗎? – adeneo

+0

嘿adeneo,是的,但顯然this.slice(0,str.length)== str;比str.indexOf('color-')=== 0 http://stackoverflow.com/a/646643/1173521 – samvv

相關問題