简体   繁体   中英

Updating data-attributes

I'm struggling to update some data-attributes in my html.

I have something like this :

<div class="navigation">
    <ul>
        <li data-content="someContent"></li>
        <li data-content="someOtherContent"></li>
     </ul>
     <ul>
        <li></li>
        <li></li>
     </ul>
 </div>

<div class="content" data-content="">
    <div class="whatever"></div>
    <input id="someID">
    <button>change TExt of div></button>
</div>

OK now when i click at one of the <li> the text which is stored in data-content is loaded in the <div class="whatever> .

Note that there is an input . This input changes the content of <div class="whatever"> .When i change the text now,the data-content of <li> still contains the old text, but i want it to be the new text, that i have put in the input-field.

My Problem is now, that i cant select the <li> anymore, because i dont have a $(this) -Objet anymore that represents the current <li> .

Some like this http://jsbin.com/tesiduhozi/5/ ? You can use .data() to store link for selected li

$(function() {
  $(document.body).on('click', 'li[data-content]', function() {
    var $this = $(this);
    var content = $this.data('content');
    $('.whatever').html(content);
    $('#someID').val(content);
    $('.whatever').data('selectedLi', $this);
  });


  $(document.body).on('click', 'button', function() {
    var $li = $('.whatever').data('selectedLi');
    var content = $('#someID').val();
    if($li) {
      $li.data('content', content);
    }  

    $('.whatever').html(content);
  });
});

In this code when you get click on li[data-content] we update '.whatever' content and store link for selected li to data for .whatever element $('.whatever').data('selectedLi', $this); .data() function allow to store any objects in associated with DOM element Hash-data object. On every new click will update this link

At any moment we can read this link from data with $('.whatever').data('selectedLi') . So on 'button' click we read this value. And if it's defined - it means that we save last clicked li element. So we can use it ( we save jQuery element ) as jQuery element

For more details - ask or read documentation at https://api.jquery.com/data/

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