如果未选中复选框,则添加属性

时间:2018-09-20 08:14:45

标签: javascript jquery

如果未选中该复选框,如何添加标题属性值“未选中”?

这是我到目前为止尝试过的 https://jsfiddle.net/5qakegrz/2/

<input type=checkbox class="fnPress" checked>1
<input type=checkbox class="fnPress">1

<script>
$(function(){
    $('input.fnPress:checked').attr("title", "selected"); 
    $('input.fnPress').change(function(){
        if($(this).is(":checked")) {
            $(this).attr("title", "selected");
        } else {
            $(this).removeAttr("title");
        }
    }); 
});

</script>

2 个答案:

答案 0 :(得分:1)

$(function() {
  var // cache selector so we don't keep scanning the DOM over and over
    $inputs = $('input.fnPress'),
    // use a function to update the "title" attribute
    update_title = function(elements) {
      // iterate over the elements given as argument
      elements.each(function() {
        // cache the element so we save one DOM scanning
        var $this = $(this);

        // change the title attribute depending on the checkbox's state
        $this.attr(
          'title',
          $this.prop('checked') ? 'selected' : 'not selected'
        );
      });
    };

  // call the function on change
  $inputs.on('change', function() {
    update_title($inputs);
  });

  // start by setting the title attributes
  update_title($inputs);
});

答案 1 :(得分:1)

要实现此目的,我们首先可以在所有复选框上添加标题not selected,然后对于选定的复选框,可以将其更新为selected。在change回调函数中,如果标题selected被选中,而未选中,则标题将为not selected。参见下面的代码。

$(function(){
    $('input.fnPress').attr("title", "not selected"); 
    $('input.fnPress:checked').attr("title", "selected"); 
    $('input.fnPress').change(function(){
        if($(this).is(":checked")) {
            $(this).attr("title", "selected");
        } else {
            $(this).attr("title", "not selected");
        }
    }); 
});
<input type=checkbox class="fnPress" checked>1
<input type=checkbox class="fnPress">1