JQuery使用title和src属性

时间:2011-01-27 13:35:07

标签: jquery function attributes each

我正在使用一个脚本,只需勾选一个复选框即可获得输入的src属性,然后浏览所有其他复选框和单选按钮.each并删除任何输入的checked属性,标题属性为是'RQlevel' + this.src。希望足够清楚。

这是我的尝试,但这不正确。

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

http://jsfiddle.net/V8FeW/

的工作示例

2 个答案:

答案 0 :(得分: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;
                }
            });
        }
    }); 
});

答案 1 :(得分: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值。如果这不是您想要的,请使用src替换each来电中的this.src,以检查当前元素的src值。