首页 > 解决方案 > Call javascript function through dynamically generated href tag (the js function has one paramter)

问题描述

I need to call getStandards() function from the dynamically generated href tag.All the code is in .js file. I went through many stackoverflow questions but I couldn't find the solution. The function has one parameter(classId) as shown below:

var ul = $('<ul></ul>');
var li = $('<li></li>');

for (var i = 0; i < classes.length; i++) {
    var classId = classes[i].classId;
    var html = "";
    html = "<li><a href='#' id='" + classId + "' onClick='getStandards(" + 
    classId + ")' >" + classes[i].className + "</a></li><br/>";
    li.append(html);
}
ul.append(li);

function getStandards(classId) {
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Can someone help me !! thank you.

标签: javascriptjquery

解决方案


我建议不要为此逻辑使用数据属性和委托事件绑定,而不是进行多个内联绑定。

var ul = $('<ul></ul>');

ul.append(
  classes.map( aClass => {
    return `
      <li>
        <a href="#" class="class-entry"
           data-class-id="${aClass.classId}">
          ${aClass.className}
        </a>
      </li>
    `;
  } )
);

ul.on( 'click', '.class-entry', event => {
  let $link = $( event.target );

  getStandards( $link.data( 'classId' ) );
} );

function getStandards(classId) {

}
  • 您可以使用 atemplate literal使您的 html 结构更具可读性
  • 将所有类映射到 html 并将它们全部附加一次,减少了附加到ul您正在执行的操作的数量
  • 将委托事件侦听器附加到ul允许您处理它的所有子项的单击,并且您可以从数据属性中获取类 ID

推荐阅读