HelloCW HelloCW - 13 days ago 5
HTML Question

Where can I store filename in li tag in html?

I list many files with li tag, I hope to I can delete and rename file, so I store filename with the code ,

but li have no value property in html5, where can I store filename in li tag in html? Thanks!

<ul>
<li value="file1">
<span onclick="Download()">Download</span>
<span onclick="Rename()">Rename</span>
</li>
<li value="file2">
<span onclick="Download()">Download</span>
<span onclick="Rename()">Rename</span>
</li>
<li value="file3">
<span onclick="Download()">Download</span>
<span onclick="Rename()">Rename</span>
</li>
</ul>

Answer

Use HTML5 data-attributes:

 <ul >
       <li data-filename="file1"> <span class ="download">Download</span>   <span class="rename">Rename</span> </li>
       <li data-filename="file2"> <span  class ="download">Download</span>   <span class="rename">Rename</span> </li>
       <li data-filename="file3"> <span  class ="download">Download</span>   <span class="rename">Rename</span> </li>
   </ul>

I would also suggest moving the click handler out of the HTML and into the javascript. This would let you save code in the html section and also give better code quality. Note that I am using jQuery below - but it can also be done in plain JS.

$(document).ready(function(){
  
  $('.download').click(function(){
    var fileName=$(this).parent().attr('data-filename');
    console.log(fileName);
    //can insert download function here
    })
  
   $('.rename').click(function(){
    var fileName=$(this).parent().attr('data-filename');
    console.log(fileName);
     //can insert rename function here
    })

  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
     <ul >
           <li data-filename="file1"> <span class ="download">Download</span>   <span class="rename">Rename</span> </li>
           <li data-filename="file2"> <span  class ="download">Download</span>   <span class="rename">Rename</span> </li>
           <li data-filename="file3"> <span  class ="download">Download</span>   <span class="rename">Rename</span> </li>
       </ul>