Javascript 单击时如何添加/删除属性

Javascript 单击时如何添加/删除属性,javascript,jquery,Javascript,Jquery,单击时如何添加/删除属性 这就是我到目前为止所尝试的 $('.btn')。单击(函数(){ $(this).attr(“title”,“selected”).sides().removeAttr(“title”,“selected”); }); 点击 点击 点击 问题是因为.btn元素不是同级元素,因此同级()不返回任何内容 要解决此问题,您可以使用closest()获取最近的共同祖先,然后find()查找.btn元素,不包括单击的元素。还要注意,removeAttr()只需要

单击时如何添加/删除属性

这就是我到目前为止所尝试的

$('.btn')。单击(函数(){
$(this).attr(“title”,“selected”).sides().removeAttr(“title”,“selected”);
});

  • 点击
  • 点击
  • 点击

问题是因为
.btn
元素不是同级元素,因此
同级()
不返回任何内容

要解决此问题,您可以使用
closest()
获取最近的共同祖先,然后
find()
查找
.btn
元素,不包括单击的元素。还要注意,
removeAttr()
只需要一个参数;要删除的属性名称。试试这个:

$('.btn')。单击(函数(){
var$btn=$(this.attr(“标题”、“选定”);
$(this).closest('ul').find('.btn').not($btn).removeAttr('title');
});

  • 点击
  • 点击
  • 点击

您的事件处理程序正常。但是,请看下面的图片。 它声明,removeAttr()函数只将属性名作为参数。 另外,您还必须为add和remove单独声明,因为attr()函数不返回jQuery对象

TLDR:

$('.btn')。单击(函数(){
$(此).attr(“标题”、“选定”);
$(this.sibbins().removeAttr(“title”);

});您可以使用.btn类从所有dom中删除标题属性,然后将标题添加到所选元素中

$('.btn')。单击(函数(){
$('.btn[title=“selected”).removeAttr(“title”)
$(此).attr(“标题”、“选定”);
});

  • 点击
  • 点击
  • 点击

删除属性时,只需指定属性的名称
因此,您需要执行以下操作:

    $('.btn').click(function() {
        $('.btn').removeAttr("title");
        $(this).attr("title", "selected");
    });

使用属性选择器选择当前选定对象

$('.btn')。单击(函数(){
$('[title=selected]')。删除标题(“title”);
$(此).attr(“标题”、“选定”);
});
[title=selected]{color:red;}

  • 点击
  • 点击
  • 点击

您应该这样做:

$('.btn').click(function() {

  //remove the selected attr from all btns
  $('.btn[title]').removeAttr('title');

  //add the title attr to the current btn
    $(this).attr('title', 'selected');

});
$('.btn').click(function() {

    //get the attr title and check later if it exist
    var attr = $(this).attr('title');

  //remove the selected attr from all btns
  $('.btn[title]').removeAttr('title');

  //add the attr only if it didnt exist before
  if(typeof attr === typeof undefined || attr === false){
        $(this).attr('title', 'selected');
  }

});

注意:此代码通常会选择一个按钮,如果希望此按钮作为复选框而不是单选按钮,则需要执行以下操作:

$('.btn').click(function() {

  //remove the selected attr from all btns
  $('.btn[title]').removeAttr('title');

  //add the title attr to the current btn
    $(this).attr('title', 'selected');

});
$('.btn').click(function() {

    //get the attr title and check later if it exist
    var attr = $(this).attr('title');

  //remove the selected attr from all btns
  $('.btn[title]').removeAttr('title');

  //add the attr only if it didnt exist before
  if(typeof attr === typeof undefined || attr === false){
        $(this).attr('title', 'selected');
  }

});

The
.removeAttr()
没有第二个参数。虽然这是真的,但不是problem@RoryMcCrossan你是对的,忽略了第一个问题。不幸的是,这个问题仍然与第一个问题相同OP@RoryMcCrossan第三个错误是,在html结构中,按钮不是同级的。我们的代码和文本不一致。我个人不会这样做建议使用“clear all
.btn
”方法,因为DOM的不同部分可能还有其他方法。@Alnitak您是对的-我在编写示例时改变了主意,忘记了更新说明:)我已将其恢复到原来的状态。