2011-01-27 68 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; 
       } 
      }); 
     } 
    }); 
});