JQuery使用title和src属性
我正在查看一个脚本,只需勾选一个复选框就会获得输入的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/上的工作示例
我想你有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”。 因此,您想要使用数据属性 。 有关工作示例,请参阅我对jsfiddle的更新 。
此外,我没有使用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; } }); } }); });
试试这个:
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
值。 如果这不是你想要的,用this.src
替换each
调用中的src
,以检查当前元素的src
值。