JQuery working with title and src attributes

半世苍凉 提交于 2020-01-25 18:42:07

问题


I am after a script that will onclick of a checkbox will get the src attribute of the input and then go through all the other checkboxes and radio buttons .each and remove the checked attribute of any inputs thats title attribute is is 'RQlevel' + this.src. Hope that is clear enough.

Here is my attempt, however it is not correct.

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

Working example at http://jsfiddle.net/V8FeW/


回答1:


I think you have your references to this confused. If I understand your question correctly, this should do what you are wanting:

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');
      }
    });
  }
}

Update:

I should have realized this earlier, but your main problem is using the src attribute as the basis of your comparison. The src attribute gets parsed so that when you query it the value will be the absolute URL. That is, instead of the value "2" you would have the value "http://example.com/2". So, you want to use a data attribute. See my update of your jsfiddle for a working example.

Also, instead of using the onclick attribute to register the event handler, I bound the handler with jQuery's .bind() method. Here is the updated 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;
                }
            });
        }
    }); 
});



回答2:


Try this:

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

Note that this should be called like this:

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

Note also that this is checking to see if the title of the element is RQlevel followed by the src value of the original clicked element. If this is not what you want, replace src in the each call with this.src to check for the src value of the current element.



来源:https://stackoverflow.com/questions/4816991/jquery-working-with-title-and-src-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!