我一直在阅读大量的问题/答案,但是无法弄清楚如何编辑它们以使其适合我。
我有一个<div id="privacy">
,我想在它之前添加一些文字。以下是一些例子,我试过了:
<script type="text/javascript">
var parent =document.getElementById('privacy')
var text=document.createTextNode('<div id="tollfree" style="left:750px;position:absolute;top:7px;font-size:18px;line-height:14px;"><strong>US Toll FREE: 1-888-555-1212<br><span style="font-size:12px;"> Promo Code "NAME"</span></strong></div>');
parent.insertBefore(text, parent);
</script>
但没有出现。我真的对javascript或jquery一无所知,所以我不确定我应该放在哪里,就像我应该把我想要添加的代码放在createTextNode之后?如此迷茫。怎么能做到这一点呢?
答案 0 :(得分:3)
使用jQuery,您可以执行以下操作
var $node = $('<div id="tollfree" style="left:750px;position:absolute;top:7px;font-size:18px;line-height:14px;"><strong>US Toll FREE: 1-888-555-1212<br><span style="font-size:12px;"> Promo Code "NAME"</span></strong></div>');
$node.insertBefore($('#privacy'));
答案 1 :(得分:2)
由于你已经标记了 jQuery,我假设你正在使用它,在这种情况下你可以这样做:
$('<your-html/>').insertBefore('#privacy');
答案 2 :(得分:1)
您应该使用不同的方法createTextNode。因为它只创建文本节点。
答案 3 :(得分:1)
Here the full documentation关于insertBefore
功能。
<div id="privacy">
...
</div>
使用jQuery
功能:
$('your_selector').insertBefore('#privacy');
答案 4 :(得分:1)
你可以这样做:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
#tollfree{
left:750px;
position:absolute;
top:7px;
font-size:18px;
line-height:14px;
}
</style>
</head>
<body>
<div id="privacy">This is pivate</div>
<script type="text/javascript">
var parent =document.getElementById('privacy'),
textDiv = document.createElement('div');
textDiv.innerHTML = '<strong>US Toll FREE: 1-888-555-1212<br><span style="font-size:12px;"> Promo Code "NAME"</span></strong>'
textDiv.setAttribute('id', 'tollfree');
parent.insertBefore(textDiv, parent.firstChild);
</script>
</body>
</html>
您还应该尝试避免使用内联CSS(正如我对div#tollfree所做的那样),如果您不得不多次执行此操作,请考虑使用模板。
答案 5 :(得分:1)
insertBefore
的工作方式是你需要在容器元素上调用它,但也要在它之前传递一个引用元素,这将是你的div
id
&#34;隐私&#34 ;.我使用innerHTML
为您要插入的新div
附加所需的标记。
var parent = document.getElementById('container');
var reference = document.getElementById('privacy');
var text = document.createElement('div');
text.id = 'tollfree';
parent.insertBefore(text, reference);
document.getElementById('tollfree').innerHTML = '<strong>US Toll FREE: 1-888-555-1212<br><span> Promo Code "NAME"</span></strong>';
另外,我会从标记中分离出这个新div
的css样式:
#tollfree {
left:750px;
position:absolute;
top:7px;
font-size:18px;
line-height:14px;
}
#tollfree span {
font-size:12px;
}
JSFiddle:http://jsfiddle.net/5fKwg/