简体   繁体   English

jQuery-用html转义符替换引号

[英]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. 表格显示了从我网站上的数据库中获取的数据,单击按钮后,将使用onclick属性调用“ enableEditing”功能。 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: 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. 这可以正常工作,但是数据库中的某些数据包含语音标记或单引号,将其更改为输入字段时会弄乱输入html。 How can I escape the html for each input field? 如何为每个输入字段转义html?

There are several ways. 有几种方法。 One of the less error-prone ones is to make jQuery/DOM do the escaping: 较不易出错的方法之一是使jQuery / DOM进行转义:

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. 您应该避免将.html()用于此类内容。 In fact, just don't use jQuery. 实际上,只是不要使用jQuery。 Vanilla JS is vastly superior - jQuery is entirely built using it! Vanilla JS非常优越-jQuery完全是用它构建的!

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. 尽管看起来似乎更多的代码,但它的运行速度至少比jQuery替代版本快一个数量级,可能是两个或三个。

jsFiddle 的jsfiddle
jsPerf jsPerf

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

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