使用jQuery查询attr()值将返回相同的

时间:2017-01-13 14:47:15

标签: jquery

我有以下HTML:

 <div data-name="name='john'">
   <span class="button">click</span>
 </div>

以下jQuery代码:

 $(".button").click(function() {
    con_sc = $(this).parent().data('name');
    alert(con_sc);
    if( con_sc.indexOf( "name='john'" ) !== -1 ) {          
        var con_new_value = con_sc.replace("name='john'","name=''");
        $(this).parent().attr("data-name", con_new_value);
    }
    if( con_sc.indexOf( "name=''" ) !== -1 ) {          
        var con_new_value = con_sc.replace("name=''","name='john'");
        $(this).parent().attr("data-name", con_new_value);
    }  
 });

上面的jQuery代码在点击按钮时将数据属性的值从name ='john'更改为name='',但是当我再次单击相同的按钮时,它会显示旧值name ='john',这是已更改为name='',它应在警报中显示name=''。我不确定我做错了什么,在Firebug中它清楚地表明它已将数据属性值更改为name=''。请指教。感谢

jsFiddle

3 个答案:

答案 0 :(得分:2)

<强> Updated fiddle

当您想要编辑data-*属性时,请使用jQuery方法 data()

$(this).parent().data("name", con_new_value);

希望这有帮助。

&#13;
&#13;
$(".button").click(function() {
  con_sc = $(this).parent().data('name');

  console.log('Current data-name is ----> '+con_sc);

  if( con_sc.indexOf( "name='john'" ) !== -1 ) {		
    var con_new_value = con_sc.replace("name='john'","name=''");	
    $(this).parent().data("name", con_new_value);

    console.log('New data-name is ----> '+$(this).parent().data("name"));
  }

  if( con_sc.indexOf( "name=''" ) !== -1 ) {
    var con_new_value = con_sc.replace("name=''","name='john'");
    $(this).parent().data("name", con_new_value);

    console.log('New data-name is ----> '+$(this).parent().data("name"));
  }  
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-name="name='john'">
  <span class="button">click</span>
</div>
&#13;
&#13;
&#13;

使用.attr()更改萤火虫中的属性:

&#13;
&#13;
$(".button").click(function() {
  con_sc = $(this).parent().attr('data-name');

  console.log('Current data-name is ----> '+con_sc);

  if( con_sc.indexOf( "name='john'" ) !== -1 ) {		
    var con_new_value = con_sc.replace("name='john'","name=''");	
    $(this).parent().attr("data-name", con_new_value);

    console.log('New data-name is ----> '+$(this).parent().data("name"));
  }

  if( con_sc.indexOf( "name=''" ) !== -1 ) {
    var con_new_value = con_sc.replace("name=''","name='john'");
    $(this).parent().attr("data-name", con_new_value);

    console.log('New data-name is ----> '+$(this).parent().data("name"));
  }  
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-name="name='john'">
  <span class="button">click</span>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用.data代替.attr更新data-属性

更新fiddle

答案 2 :(得分:0)

为什么不设置这样的数据:$(this).parent().data('name', '')