简体   繁体   中英

JQuery - Replace quotes with html escape

A table shows data grabbed from a database on my site, when a button is clicked the "enableEditing" function is called using the onclick attribute. Then for one field for each row in the the table, an input textbox appears using the field as the value, and the key as the input name.

Before:

<tr class="data_row">
    <td class="property_cell">project ref</td>
    <td class="myNumber">200407</td>
</tr>

After:

<tr class="data_row">
    <td class="property_cell">project ref</td>
    <td class="myNumber">
        <input name="project ref" value="200407">
    </td>
</tr>

jQuery:

function enableEditing(){

    $("#object_data tr").each(function(){
        var key = $(this).children(".property_cell").html();
        var value = $(this).children(".myNumber").text();
        $(this).children(".myNumber").html("<input name='" + key + "' value='" + value + "'>");
    });
}

This works fine, however some of the data from the database contains speech marks or single quotes, which when changed to an input field will mess up the input html. How can I escape the html for each input field?

There are several ways. One of the less error-prone ones is to make jQuery/DOM do the escaping:

var input = $('<input name="'+key+'">');
input.val(value);
$(this).children(".myNumber").empty().append(input);

Try

$('.myNumber').contents().replaceWith(function(){
    return $('<input />', { name: $(this).parent().prev().text(), value : $(this).text()});
})

Demo: Fiddle

You should avoid using .html() for something like this. In fact, just don't use jQuery. Vanilla JS is vastly superior - jQuery is entirely built using it!

var rows = document.getElementById('object_data').rows, l = rows.length, i, td, inp;
for( i=0; i<l; i++) {
    td = rows[i].cells[1];
    if( !td.className.match(/\bmyNumber\b/)) continue; // failsafe
    inp = document.createElement('input');
    inp.type = "text";
    inp.name = rows[i].cells[0].firstChild.nodeValue;
    inp.value = td.firstChild.nodeValue;
    td.replaceChild(inp,td.firstChild);
}

While it may seem like more code, it will run at least an order of magnitude, possibly two or three, faster than the jQuery alternative.

jsFiddle
jsPerf

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