简体   繁体   中英

Remove data-attr of cloned element

I'm trying to make a very simple (it looks like) thing: clone already existring html-element, modify it's attribute and append in on the page. And it doesn't work, and I have no idea why.

Here is a simple demo:

Hello World

Change color

 // js var banner = $("#banner-message") var button = $("button") // handle click and add class button.on("click", function(){ var row = $('#banner-message').find('.test:first').clone(true); row.removeData('event-num'); //row.data('event-num', 500); $('#banner-message').find('.test:last').after(row); }) 

Here is a jsfiddle demo: https://jsfiddle.net/jn1wm9da/

It neither deletes nor overrides (actually I want to delete it) already existing attribute. What I'm doing wrong?

jQuery's .data() method stores information in a jQuery object that is connected to the element, and doesn't effect data-* attributes. Data attributes are just attributes, and you should use .attr() , and .removeAttr() to add/change or remove them.

 // find elements var banner = $("#banner-message") var button = $("button") // handle click and add class button.on("click", function() { var row = $('#banner-message').find('.test:first').clone(true); row.removeAttr('data-event-num'); row.attr('data-event-num', 500); $('#banner-message').find('.test:last').after(row); }) 
 body { background: #20262E; padding: 20px; font-family: Helvetica; } #banner-message { background: #fff; border-radius: 4px; padding: 20px; font-size: 25px; text-align: center; transition: all 0.2s; margin: 0 auto; width: 300px; } button { background: #0084ff; border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; color: #fff; } #banner-message.alt { background: #0084ff; color: #fff; margin-top: 40px; width: 200px; } #banner-message.alt button { background: #fff; color: #000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="banner-message"> <p>Hello World</p> <button class="test" data-event-num='0'>Change color</button> </div> 

From the jQuery Documentation for removeData

Note that .removeData() will only remove data from jQuery's internal .data() cache, and any corresponding data- attributes on the element will not be removed.

Try using

row.removeAttr('data-event-num');

instead

Use row.attr('data-event-num', null); to remove the data attribute

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
  var row = $('#banner-message').find('.test:first').clone(true);
  //row.removeData('event-num');
  row.attr('data-event-num', null);
  $('#banner-message').find('.test:last').after(row);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM