【问题标题】:JQuery working with title and src attributesJQuery 使用 title 和 src 属性
【发布时间】:2011-06-16 13:31:02
【问题描述】:

我在一个脚本之后,该脚本将单击复选框将获取输入的 src 属性,然后遍历所有其他复选框和单选按钮 .each 并删除标题属性为 @ 的任何输入的选中属性987654323@。希望这已经足够清楚了。

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

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

http://jsfiddle.net/V8FeW/ 的工作示例

【问题讨论】:

  • 这个有点不清楚,可以举个例子吗?

标签: jquery function attributes each


【解决方案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。也就是说,您将拥有值“http://example.com/2”,而不是值“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;
                }
            });
        }
    }); 
});

【讨论】:

  • 这样做的目的是什么:var $this = $(this);
  • 这看起来不错,但似乎不起作用。我已经做了一些诊断,但无法弄清楚。这是实现代码的链接。如果您选中两个复选框,然后取消选中两个复选框中的第一个,则两个复选框中的第二个也应取消选中。访问 ::divethegap.com/update/diving-trips/adventure-training 并点击 BEGINNERS 加载表单
  • 请在 jsfiddle.net 创建一个示例。
  • @Robin,我已经更新了我的答案以解决 jsfiddle 中显示的问题。
【解决方案2】:

试试这个:

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 值。如果这不是您想要的,请将 each 调用中的 src 替换为 this.src 以检查当前元素的 src 值。

【讨论】:

  • 不,你对我所追求的完全正确,但是当我测试它时,我发现我无法取消选中本来会取消选中另一个框的框。它根本不允许我取消选中它。
猜你喜欢
  • 2018-09-30
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 2015-04-18
相关资源
最近更新 更多