2011-01-27 72 views
0

我在腳本後點擊一個複選框將獲得輸入的src屬性,然後遍歷所有其他複選框和單選按鈕.each並刪除任何輸入的checked屬性標題屬性是'RQlevel' + this.src。希望是夠清楚的。JQuery使用標題和src屬性

這是我的嘗試,但它是不正確的。

function levels() { 
    if ($(this).is(':not(:checked)').each(function()) { 
     if($(':input').attr('title', 'RQlevel' + this.src) { 
     $(':input').removeAttr('checked'); 
     }); 
    });  
} 

工作在http://jsfiddle.net/V8FeW/

+0

這有點不清楚,你能提供一個例子嗎? – Brayn 2011-01-27 13:40:15

+0

http://jsfiddle.net/V8FeW/ – 2011-01-27 14:26:02

回答

0

例子試試這個:

function levels() { 
    if (!this.checked) { 
     var src = this.src; 
     $('input:checkbox, input:radio').each(function(){ 
      if (this.title === 'RQlevel' + src) { 
       this.checked = false; 
      } 
     }); 
    } 
} 

注意,這應該被稱爲是這樣的:

$('#yourCheckbox').click(levels); 

還要注意的是,這是檢查是否元素的標題是RQlevel,後面是src的值e原始點擊元素。如果這不是您想要的,請用this.src替換src中的each調用以檢查當前元素的src值。

+0

不,你是完全正確的,但是當我測試它後,我發現我無法取消勾選另一個框也沒有選中的框。它根本不會讓我不檢查它。 – 2011-01-27 14:13:04

1

我想你有你的參考this困惑。如果我沒有理解你的問題,這應該做你想要什麼:

function levels() { 
    var $this = $(this); // Cache a reference to the element that was clicked 
    if ($this.is(':not(:checked)') { // Determine if the clicked element is checked 
    $(':input').each(function() { // Loop through every input element 
     // Here, 'this' is the current element in the loop and 
     // '$this' is the originally clicked element. 
     if (this.title === ('RQLevel' + $this.attr('src'))) { 
     $(this).removeAttr('checked'); 
     } 
    }); 
    } 
} 

更新:

我應該意識到這個較早,但你的主要問題是使用src屬性爲基礎你的比較。 src屬性被解析,因此當您查詢它時,該值將是絕對URL。也就是說,而不是值「2」,您將有值「http://example.com/2」。所以,你想使用一個data attribute。查看你的jsfiddle的我的update作爲一個工作示例。

此外,我沒有使用onclick屬性來註冊事件處理程序,而是使用jQuery的.bind()方法來綁定處理程序。這裏是更新的JavaScript:

$(function() { 
    $(':input').bind('click', function() { 
     var src = $(this).data('src'); 

     if (!this.checked) { 
      $('input:checked').each(function(){ 
       if (this.title === ('RQlevel' + src)) { 
        this.checked = false; 
       } 
      }); 
     } 
    }); 
});