Javascript .html()与.innerHTML
我在做一个文本编辑器。当用户双击特定的Javascript .html()与.innerHTML,javascript,jquery,Javascript,Jquery,我在做一个文本编辑器。当用户双击特定的时,contentEditable属性设置为true,并显示一些编辑器工具。然后,用户可以在单击“保存”和“退出”之间进行选择。如果他逃跑了,我想还原此中以前的数据。因此,我在第一次双击(temp['htmlText'])时复制数据,然后: $('#esc').click(function() { var confEsc = confirm('---\n\nSouhaitez-vous quitter sans enregistrer vos mod
时,contentEditable
属性设置为true
,并显示一些编辑器工具。然后,用户可以在单击“保存”和“退出”之间进行选择。如果他逃跑了,我想还原此
中以前的数据。因此,我在第一次双击(temp['htmlText']
)时复制数据,然后:
$('#esc').click(function() {
var confEsc = confirm('---\n\nSouhaitez-vous quitter sans enregistrer vos modifications ?\n\n---');
if(confEsc) {
//Do you know why that works :
var id = document.getElementById(temp['myId']);
id.innerHTML = temp['htmlTxt'];
//and why that doesn't work ?
$('#'+temp['myId']).html(temp['htmlTxt'])
}
});
我不明白为什么它可以很好地使用经典JavaScript而不是jQuery…我认为它完全取决于temp['htmlText']的内容。我见过有人试图使用.html()将javascript注入页面(作为类似
的标记),但jQuery去掉了这一点
但另一方面,DOM不是字符串,这可能是不受欢迎的。innerHTML很容易在较旧的浏览器中泄漏。考虑使用与.nNeldHTML
不同的属性。这2个实际上是相同的。然而,jQuery做了一些可能会妨碍您的预处理
jqueryglobalsrnoInnerHtml = /<(?:script|style)/i;
rtagName = /<([\w:]+)/;
rleadingWhitespace = /^\s+/;
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
wrapMap = {
"option": [1, "<select multiple='multiple'>", "</select>"],
"legend": [1, "<fieldset>", "</fieldset>"],
"thead": [1, "<table>", "</table>"],
"tr": [2, "<table><tbody>", "</tbody></table>"],
"td": [3, "<table><tbody><tr>", "</tr></tbody></table>"],
"col": [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"],
"area": [1, "<map>", "</map>"],
"_default": [0, "", ""],
"optgroup": [1, "<select multiple='multiple'>", "</select>"],
"caption": [1, "<table>", "</table>"],
"colgroup": [1, "<table>", "</table>"],
"tfoot": [1, "<table>", "</table>"],
"tbody": [1, "<table>", "</table>"],
"th": [3, "<table><tbody><tr>", "</tr></tbody></table>"]
};
rnoInnerHtml=/temp['htmlText']
等于什么?您能创建一个JSFIDLE吗?同时,temp['htmlTxt']
的值是多少?您也可以显示您的html吗?使用JQuery时具体发生了什么?它是否将其设置为空?根本不改变它?踢你的小狗?你在chrome控制台或firebug中收到任何错误消息吗?老实说,我看不出有什么不对
var elem = this[0] || {},
i = 0,
l = this.length;
if (typeof value === "string" && !rnoInnerhtml.test(value) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) &&
!wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for (; i < l; i++) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if (elem.nodeType === 1) {
jQuery.cleanData(elem.getElementsByTagName("*"));
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if (elem) {
this.empty().append(value);
}