简体   繁体   中英

White space in onclick value causes incorrect HTML

I am using below JavaScript code to append <tr> row to <table> :

<script type="text/javascript">
    function addRow() {
        var filesName = 'Document Draft.png'
        var newRow = "<tr><td>td Data 1</td><td><a onclick=deleteDocument(this,'" + filesName + "')>Delete</a></td></tr>";
        $("#idDocList").append(newRow);
    } 
</script>

This code adds one tr to table .

Problem: But the issue is that filesName has one white space which is wrongly render on DOM as below:

<tr>
    <td>td Data 1</td>
    <td>
        <a onclick="deleteDocument(this,'Document" Draft.png')"">Delete</a>
    </td>
</tr>

So the onclick doesn't work because rendered HTML is

onclick="deleteDocument(this,'Document" Draft.png')

As you can see in above line, it will take ( " ) instead of white space. How to fix it?

Since you have spaces in onclick property value, you should wrap its value with, for example, "" :

...<a onclick=\"deleteDocument(this,'" + filesName + "')\">...

Fiddle example .

Instead of inline JS onclick="" (which is discouraged nowdays), you can use jQuery's .on("click") :

var filesName = 'Document Draft.png';
var newRow = "<tr><td>td Data 1</td><td><a class='delete'>Delete</a></td></tr>";
$("#idDocList").append(newRow);

$('#idDocList').on('click', ".delete", function()
{
    deleteDocument(this, filesName);
});

Fiddle example .

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