简体   繁体   中英

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. This function should be called when the user clicks on a link that looks like an "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.

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

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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