Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

Javascript variable to html data attribute

I am looking to be able to pass a javascript variable as data in an html table row element and have the data logged when that row element is click. The code that is appending/creating the table rows is inside an ajax call. Outside of the call in a click function I want to click on a table row that was created/appened and get the data variable. Here is the current code

$.ajax({ 
...
  var name = 'superman'
  $('#myTable tbody').append('<tr class = 'table_class' id = 'table_id' data-person = name></tr>');
  });
...
$('#myTable tbody').on('click','table_class', function(){
    console.log($(this).dataset.name);
}

The expected result of the console log is to be: superman.

question from:https://stackoverflow.com/questions/66049681/javascript-variable-to-html-data-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are adding the class to the <tr>, make sure you include at least one <td> child so that you can actually click on the row.

var table_id = 'table_id';
var table_class = 'table_class';

// AJAX logic start...
var name = 'superman';
$('#myTable tbody').append(
  $('<tr>')
  .attr('id', table_id)
  .addClass(table_class)
  .data('person', name)
  .append(
    $('<td>').text(name)
  )
);
// AJAX logic end...

$('#myTable tbody').on('click', `.${table_class}`, function() {
  console.log($(this).data('person'));
});
#myTable { border-collapse: collapse; }

#myTable, #myTable th, #myTable td { border: thin solid grey; }

#myTable th, #myTable td { padding: 0.5em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...