我正在編寫一個基本的web應用程序,它有一些列表元素,我需要能夠點擊圍繞每個元素的整個LI來選擇內部的單選按鈕,只確保我點擊的那個被選中。我可以在.click回調中編寫代碼,但是如果我嘗試從命名函數調用相同的代碼,它會掉下來,我相信這是與我使用的「this」引用有關的,但是我不能似乎修復它。在功能問題中使用的jquery'this'
的HTML是
<ul>
<form id="healthCheckAge" name="healthCheckAge">
<li> <input type="radio" name="eighteen" value="18-30" />18-30 </li>
<li> <input type="radio" name="thirtyone" value="31-45" />31-45 </li>
<li> <input type="radio" name="fourtysix" value="46-65" />46-65 </li>
<li> <input type="radio" name="sixtyfive" value="65+" />65+</li>
</form>
</ul>
和JavaScript是
function li_click(){
//set the vars for the selectors
var listInputs = $('#healthCheckAge li input');
var clicked = listInputs.attr('name');
//loop on all the li children to see if they match the clicked LI - if not ensure that they are unchecked and faded
$(listInputs).each(function(index,Element){
$(listInputs).attr('checked',false).parent().addClass('selected');
});
//set the radio button to checked and apply a style to it, while removing this from any other checked radio buttoon
if($(listInputs).attr('name')==clicked){
$(this).children().attr('checked','true').parent().removeClass('selected');
}
}
$('#healthCheckAge li').click(function(){
li_click();
});
我認爲問題是,當我打電話的最後條件語句中的「本」是不是反映了我所需要的。
任何想法?
您使用的是Firebug或Chrome開發工具嗎? – Chev 2010-11-14 17:01:48
我一直在爲iPad開發,所以一直使用Safari,雖然我有鉻,這應該在那裏工作。我一直在safari中爲jquery運行JSLint,並且控制檯抱怨說「沒有找到與'undefined'選擇器相關的元素」,如果我在.click回調中運行相同的代碼,則不會收到這些元素。如果我運行if($(listInputs).attr('name')== click){alert(this.nodeName)\t \t \t \t \t \t $(this).children()。attr('checked' 。 '真')的父()removeClass( '選擇')。 \t}' 我得到的節點名稱未定義 - 所以我有點需要找到一種方法,使其與條件語句相關:/ – user499846 2010-11-14 17:10:47
在整個複雜功能需要這種情況下避免問題的最佳方法是設置一個變量到這個像'var __this = $(this)這樣的valye;' – 2010-11-14 17:13:23