2012-10-30 45 views
1

我會用代碼解釋我的情況。jQuery:如何在多個SELECT元素中預先加載一個OPTION,如果它已經不在那裏?

HTML:

<div class="list1"> 
    <select class="select250"> 
    <option class="temp" selected="selected" name="filter[]">Select</option> 
    <option class="" value="George" name="filter[]">George</option> 
    <option class="" value="Ben" name="filter[]">Ben</option> 
    </select> 
</div> 
<div class="list2"> 
    <select class="select251"> 
    <option class="temp" selected="selected" name="filter[]">Select</option> 
    <option class="" value="Sarah" name="filter[]">Sarah</option> 
    <option class="" value="Alex" name="filter[]">Alex</option> 
    <option class="" value="Natalie" name="filter[]">Natalie</option> 
    </select> 
</div> 
<div class="list3"> 
    <select class="select252"> 
    <option class="temp" selected="selected" name="filter[]">Select</option> 
    <option class="" value="Mobile" name="filter[]">Mobile</option> 
    <option class="" value="Car" name="filter[]">Car</option> 
    <option class="" value="Computer" name="filter[]">Computer</option> 
    </select> 
</div> 

JS(這是PHP中使用):

<script type="text/javascript"> 
    $('.select<?php echo $sid?>').change(function() { 
    $('.temp', this).remove(); // THIS IS FINE 
    if ($('option').siblings('.temp')) { } 
    else { $('select').prepend('<option name="filter[]" selected="selected" class="temp">Select</option>'); // THIS IS NOT WORKING 
    } 
    }); 
</script> 

我想要做的是 - 只要選擇一個選項,它應該刪除 「選擇」 選項在該列表中但仍保持其他列表上的「選擇」選項。這部分似乎工作正常。接下來要做的是 - 當在另一個列表上選擇一個選項時,它應該在所有其他列表上選擇,除了它所在的列表之外。我試着爲它編寫一個代碼,就像你上面看到的那樣,但是不能移過去。如果有人能指引我朝着正確的方向發展,那會很棒。謝謝。

+0

我不知道爲什麼,但我當我看到php和js被混合在一起時總是得到意志。 –

回答

3

試試這個..這仍然可以優化..

$('[class^=select]').on('change', function() { 
    $('.temp', this).remove(); 
    var $that = $(this); 
    $('select').not($that).each(function() { 
     if (!$(this).find('option.temp').length > -1) { 
      $(this).prepend('<option name="filter[]" selected="selected" class="temp">Select</option>'); 
     } 
    }); 
});​ 

Check Fiddle

+0

這很棒 - 你的小提琴代碼可以工作!正是我需要的。您的小提琴代碼與您上面粘貼的代碼有點不同。您的上面的行:if(!$(this).find('option.temp')。length> -1)不起作用。我不得不使用> 0或根本不使用(就像在你的Fiddle代碼中)。 – user1448031

+0

我剛剛注意到,在Opera和IE瀏覽器中,你的代碼似乎不起作用。在Opera和IE中嘗試你的小提琴代碼。有關如何解決這個問題的任何建議? – user1448031

+0

我嘗試過在IE7,IE8和IE9中測試它,它似乎在爲我工作。將屬性選擇器放入引號中,然後再試一次$('[class^=「select」]') –

1

怎麼是這樣的:

$('select').not($(this)).each(function() { 
if ($(this).find('.temp').size() > 0) continue; 

$(this).prepend('<option class="temp" ... </option>'); 
}); 
相關問題