使用jQuery从HTML中删除数据属性 [英] Removing data attributes from HTML using jQuery

查看:76
本文介绍了使用jQuery从HTML中删除数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎无法让这个工作......

Can't seem to get this one to work...

我有一个隐藏某些链接的页面。当加载DOM时,我正在使用jQuery来切换其中的一些元素。这是通过使用如下数据属性来驱动的:

I have a page that hides certain links. When the DOM is loaded, I'm using jQuery to toggle some of those elements. This is driven by using a data attribute like so:

<div class="d_btn" data-usr='48'>
  <div class="hidden_button">

然后,我有代码:

  $.each($(".d_btn"), function() {
     var btn = $(this).data('usr');
   if ( btn == '48' ){      
     $(this).children('.hidden_button').toggle();
   }

以上都按计划工作。问题是我试图在评估if语句时从类.d_btn中删除数据usr。我试过了以下和没有任何作用(即,在页面加载后,源仍然显示data-usr属性:

The above all works as planned. The problem is that I am trying to remove the data-usr from the class .d_btn once the if statement is evaluated. I've tried the following and nothing works (i.e., after the page is loaded, the source still shows the data-usr attribute:

$(this).removeAttr("data-usr");

$(this).removeData("usr");

我一直在努力工作几个小时而且......没有!非常感谢帮助!

I've been working on this for a couple of hours now and...nothing! Help is greatly appreciated!

更新

我已经尝试过将数据属性设置为空字符串的好建议,但我仍然没有得到所需的结果。

I've tried the great suggestions of setting the data attribute to an empty string but I'm still not getting the desired result.

为了进一步解释,我试图删除该属性的原因是当ajax响应向页面添加另一个项目时,之前添加的项目已经具有按钮显示或隐藏。在AJAX响应时,我在加载DOM时调用相同的函数。

To explain a little further, The reason I'm trying to remove the attribute is so when an ajax response adds another item to the page, the previously added items would already have the button either shown or hidden. Upon AJAX response, I'm calling the same function once the DOM is loaded.

目前,当通过AJAX添加某些内容时,它会切换所有按钮(显示那些按钮)这是隐藏的,反之亦然。)呃...

Currently, when something is added via AJAX, it toggles all the buttons (showing the ones that were hidden and vice versa.) Ugh...

我也完全愿意尝试替代我的方法。谢谢!

I'm also fully willing to try alternatives to my approach. Thanks!

更新

UPDATE

嗯,灯泡刚闪过,我只能用.show()而不是.toggle()来做我想做的事。

Well, the light bulb just flashed and I am able to do what I want to do by just using .show() instead of .toggle()

无论如何,我还是喜欢找到这个问题的答案,因为无论什么时候添加东西,页面都可能会检查数百个项目 - 这看起来非常低效(即使是电脑,哈哈哈。)

Anyway, I'd still like to find an answer to this question because the page will be potentially checking hundreds of items whenever something is added - this seems horribly inefficient (even for a computer, hahaha.)

推荐答案

更改DOM不会影响源。它会影响DOM,您可以使用Inspector / Developer Tools查看它。右键单击=>查看源代码将为您提供页面的原始来源,而不是JavaScript修改的实际当前来源。

Changing the DOM doesn't affect the source. It affects the DOM, which you can view with the Inspector/Developer Tools. Right click => View Source will give you the original source of the page, not the actual current source as modified by JavaScript.

这篇关于使用jQuery从HTML中删除数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆