javascript - 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.
解决方案
我建议不要为此逻辑使用数据属性和委托事件绑定,而不是进行多个内联绑定。
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) {
}
- 您可以使用 a
template literal
使您的 html 结构更具可读性 - 将所有类映射到 html 并将它们全部附加一次,减少了附加到
ul
您正在执行的操作的数量 - 将委托事件侦听器附加到
ul
允许您处理它的所有子项的单击,并且您可以从数据属性中获取类 ID
推荐阅读
- javascript - 陷入 eslint 错误,即单独地,应避免循环以支持数组迭代
- apache-spark - 如何使用 Spark 创建从 Kafka 到 Hdfs 的数据湖 - 存储在自定义目录中?
- sql-server - 无法保存对 INSERTed 记录的更改
- reactjs - reactjs中如何将数据从子组件发送到父组件
- python - 如何在 KERAS 中计算 PSNR 指标
- python - 什么是所谓的“缩小”多边形的操作?
- android - Clang 分析器缺少内存泄漏
- php - JSON 不发送到文件
- scala - Scala groupby key sum value over a Seq of (key, value) 同时保持 Order
- spring-boot - DB关闭时如何将任何下载的文件路由到错误通道以及DB启动后如何处理它们?