简体   繁体   English

使用多个参数从 HTML 调用 javascript 函数

[英]Calling javascript Function from HTML with multiple parameters

I'm trying to call a javascript function called confirmRemove(title, id) to remove an element from a table.我正在尝试调用一个名为 confirmRemove(title, id) 的 javascript 函数来从表中删除一个元素。 This function should be called when the user clicks on a link that looks like an "X".当用户单击看起来像“X”的链接时,应调用此函数。 I attached my code below to show how I went about doing this, but I'm seeming to be having some errors and I'm not sure why.我在下面附上了我的代码来展示我是如何做到这一点的,但我似乎遇到了一些错误,我不确定为什么。 Most of the elements are able to be removed, but for a few when I click the link to call the function, nothing happens.大多数元素都可以删除,但是当我单击链接调用函数时,有一些元素没有任何反应。 Is there a better way of doing this?有更好的方法吗? Not sure why this would happen.不知道为什么会这样。

<td><?php echo '<a onclick="confirmRemove(\'' . $title . '\',\'' . $id . '\')" 
href="javascript:void(0)">X</a>';?></td>

You can try this code你可以试试这段代码

<td> <a onclick="confirmRemove('<?php echo $title; ?>','<?php echo $id; ?>')" 
   href="javascript:void(0)">X</a></td>

You asked if there is a better way of doing this - I would suggest that there is and that it is to use an externally registered event handler bound to the specific HTML elements in question - notably a hyperlink in this example.您询问是否有更好的方法来执行此操作 - 我建议有并且它是使用绑定到所讨论的特定 HTML 元素的外部注册事件处理程序 - 特别是本例中的超链接。

If you assign relevant attributes to the hyperlink ( dataset attributes are very useful for this sort of task ) you can process them within your event listener very easily.如果您将相关属性分配给超链接(数据集属性对于此类任务非常有用),您可以非常轻松地在事件侦听器中处理它们。 There is not need for complicated escaping for quotes by adopting this approach and best of all you can separate HTML from Javascript - the event handlers can be in another file采用这种方法不需要对引号进行复杂的escaping ,最重要的是你可以将 HTML 与 Javascript 分开——事件处理程序可以在另一个文件中

<td>
    <a class='removal' href='javascript:void(0)' data-title="<?php echo $title;>" data-id="<?php echo $id;?>">X</a>
</td>


<script>
    Array.from( document.querySelectorAll('a.removal') ).forEach( a=>{
        a.addEventListener('click',function(e){
            confirmRemove( this.dataset.title, this.dataset.id )
        });
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM