2016-08-01 32 views
-1
$(document).ready(function(){ 
$('#switcher-default').addClass('selected'); 
$('#switcher button').on('click', function(){ 

    var bodyClass = this.id.split('-')[1]; 

    $('body').removeClass().addClass(bodyClass); 
    $('#switcher button').removeClass('selected'); 
    $(this).addClass('selected'); 
    console.log(bodyClass); 
}); 
}); 

//////////////Html Code///////////// 

<div id="switcher" class="switcher"> 
    <h3>Style Switcher</h3> 
    <button id="switcher-default"> 
     Default 
    </button> 
    <button id="switcher-narrow"> 
     Narrow Column 
    </button> 
    <button id="switcher-large"> 
     Large Print 
    </button> 
</div> 

此代碼的作品,我可以看到它做了什麼,但方括號中的1令我困惑。這是否意味着拆分使用「 - 」的ID並取第一部分?我真的不知道?會提供幫助。有人可以向我解釋這個jQuery代碼中的方括號是什麼嗎?

+4

'split()返回* n *個元素的數組,'[i]'訪問該數組的第i個元素。 –

+0

正如附註一樣,ID不應該帶任何數據。你有'data- *'屬性。所有這些說這個代碼是不好的 –

+0

@ A.Wolff:我不會說「從不」。如果你因爲其他原因需要一個'id'作爲你的元素,並且你還需要知道這個元素所代表的東西的唯一標識符(比如博客評論),我看不出有什麼問題使得這個id成爲id的一部分(如他們在[本MSDN博客文章]中的評論中所做的那樣)(https://blogs.msdn.microsoft.com/vcblog/2014/06/03/visual-studio-14-ctp/#div-comment-77733) )。 –

回答

0

這意味着你將由this.id標識的字符串分開,這將導致數組。您可以使用該數組中索引爲1的值來設置變量bodyClass

請注意,在許多設置中,如果您不是生成所有數據的設置,則假定結果數組始終具有特定數量的元素可能是不安全的。

0

this.id.split('-')的結果是一個數組。因此[1]檢索索引1

將相當於該項目:

//get array of ids 
var ids = this.id.split('-'); 
//get 1st id 
var bodyClass = ids[i]; 
0

this.id可以是 '切換-無論' this.id.split('-')是等於[ '切換', '無論'] this.id.split('-')[1]是取第二個元素'whatever'

+0

謝謝。這有助於我理解它。 –

相關問題