JavaScript 外部 HTML : How to work with a string literal?

标签 javascript html string outerhtml

首先是一些 HTML 代码:

<div id="content_4" class="content" style="background:url(pic1.gif)"></div>
<div id="content_4_a" class="content" style="background:url(pic2.gif);
    display:none"></div>

这是 JS 代码:

function getOuterHMTL(element){
    return element.outerHTML;
}

function switchDisplayOuter(elementToHide, elementToShow, stringly){
    document.getElementsByName(elementToShow).outerHTML=stringly;
    document.getElementById(elementToHide).style.display="none";
    document.getElementsByName(elementToShow)[0].style.display="";
}

现在这个 HTML 代码可以工作了(当我点击它时,div 切换并且图片发生变化):

<area shape="rect" coords="0,252,98,337" onMouseOver="switchDisplayOuter(
    'content_4', 'content_4_a', getOuterHMTL('content_4_a) )">

但不是这个:

<area shape="rect" coords="0,252,98,337" onMouseOver="switchDisplayOuter(
    'content_4', 'content_4_a', '<div id="content_4_a" class="content" 
    style="background:url(pic2.gif); display:none"></div>' )">

在 Firefox 中调试时它只会给我一个错误代码:

Error: SyntaxError: unterminated string literal
'<div id=

有人知道正确的代码而不使用函数 getOuterHMTL(element) 但使用“纯”字符串文字吗?

最佳答案

您需要将 onMouseOver 属性值中的 " 替换为 \':

<area shape="rect" coords="0,252,98,337" onMouseOver="switchDisplayOuter('content_4', 'content_4_a', '<div id=\'content_4_a\' class=\'content\'  style=\'background:url(pic2.gif); display:none\'></div>' )">

这是因为您的 area 标记的 onMouseOver 属性值包含在 " 中。

关于JavaScript 外部 HTML : How to work with a string literal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637954/

相关文章:

php - 如何将大量字符串与另一个字符串的开头进行比较?

javascript - react redux 更新状态 onClick 函数与多个 Action

javascript - 展开 <UL> <LI> 工作正常,但如果有链接,它也会默认单击然后展开,但情况并非如此

html - Bootstrap Navbar 链接背景高度

string - 快速打印字符串插值和文件夹路径

c# - 如何缩小字符串并在以后找到原始字符串

javascript - d3js - 如何将 x- 域值向右移动

javascript - FireBug DOM 颜色是什么意思?

html - 清除 md-select 箭头溢出的按钮

HTML 多选限制