我指的是其他类似的讨论。下面是讨论的链接。
外部HTML运行良好。但我的要求是内部HTML。不使用外部HTML的原因是我使用的是AngularJS,它具有HTML本身的条件。所以我需要将内容添加到innerHTML中。
这是HTML。
<p ng-show="preview=='text' && !file.showUploadPanel && file.fileContent!='null' && file.fileContent!='undefined'" ng-bind-html-unsafe="file.fileContent" class="pre fileContent"></p>以下是支持它的JS。
var elem = $(".pre.fileContent")[1];
if (elem.tagName == "P" && "innerHTML" in elem){
elem.innerHTML = "<pre>" + elem.innerHTML + "</pre>";
}我还尝试用导致"<pre>" + $scope.file.fileContent + "</pre>";的作用域变量替换"<pre>" + $scope.file.fileContent + "</pre>";
下面是我在IE8上遇到的错误。
Error: Unknown runtime errorundefined如果我从<pre>中删除elem.innerHTML,错误就不会发生。另外,对于outerHTML,这个错误不会出现。
我该怎么处理呢?
发布于 2013-05-09 04:54:29
看起来您只是想将内容包装在pre元素中吗?如果是这样的话,你可以这么做:
var pre = document.createElement('pre');
while(elem.firstChild) pre.appendChild(elem.firstChild);
elem.appendChild(pre);这有一个额外的好处:保留任何属性值和事件处理程序。
或者,您只需将CSS应用于相关元素:
white-space:pre;
font-family:monospace;编辑: CSS解决方案可能更好--我不认为在<pre>标记中包含块级元素<p>是有效的。
发布于 2013-05-12 03:33:42
其实我自己找到了答案。在使用AngularJS时,我使用了错误的ng-bind-html-unsafe指令。我把ng-bind-html-unsafe换成了ng-bind,然后我的问题就解决了!
谢谢大家的帮助!
发布于 2013-05-10 05:51:42
抱歉,我和段落类选择器搞混了,
<p ng-show="preview=='text' && !file.showUploadPanel && file.fileContent!='null' && file.fileContent!='undefined'" ng-bind-html-unsafe="file.fileContent" class="pre fileContent"></p>上面的<p>标记包含类".pre“和".filecontent”,您正在尝试使用选择器$(".pre.fileContent")来查找在类".pre“的元素中包含".fileContent”类的元素。
我只想确定它是正确的还是错误的。:)
解决方案:
获取文本区域或源容器中的内容,将字符串拆分为"\n“,并通过循环向所有数组元素添加<p>标记。
var textVal = jQuery("#wmd-input").val();
textVal = textVal.split("\n");
var temp = "";
for (var i=0; i < textVal.length; i++) {
temp += "<p>" + textVal[i] + "</p>";
}
/* Assing the temp html in your target div or container*/https://stackoverflow.com/questions/14432257
复制相似问题