转换<a>使用jQuery将文本字符串转换为dom元素
convert <a> text string to dom element with jQuery
如何将链接中的文本转换为html元素?
我用
$('a').text();
来定位文本,它返回值,但我无法向其中添加元素。
我试过这个:
var someText = $('a').text();
var theElement = $('< p >' + someText + '< /p >');
someText.replaceWith(theElement);
我知道这应该会在链接中添加一个文本元素,这不是最佳实践,但甚至不起作用。
我真正需要的是删除整个文本,并在取消链接后立即将其重写为文本元素。
任何帮助都将不胜感激。谢谢
标记:
<li>
<a href="/"> <img src="image.png"> text to be converted to element </a>
</li>
我想要什么:
<li>
<a href="/"> <img src="image.png"></a>
<p> text to be converted to element </p>
</li>
由于someText
是一个字符串,而不是jQuery元素,因此不能对其调用.replaceWith()
var someLink = $('a');
var someText = someLink.text();
var theElement = $('<p>' + someText + '</p>'); // no spaces inside tags
someLink.replaceWith(theElement);
http://jsfiddle.net/0xxrL6zy/
更新由于您在问题中添加了新信息,以下是满足您需求的解决方案:
var someLink = $('a');
var someText = someLink.text();
var someImg = someLink.find('img');
var theElement = $('<p>' + someText + '</p>');
someLink.html(someImg).after(theElement);
http://jsfiddle.net/mblase75/mzbtr0qp/1/
http://jsfiddle.net/cvgbqb8b/2/
var anchor = $('li a');
anchor.after('<p>' + anchor.text() + '</p>')
.contents()
.filter(function(){
return (this.nodeType == 3);
})
.remove();
在此处找到了删除文本的代码https://stackoverflow.com/a/17852238/1415091
我建议:
// iterate over each of the <a> elements within <li> elements:
$('li a').each(function() {
// create a <p> element, setting its text
// to that of the 'this' element (the <a>):
$('<p>', {
'text': this.textContent
// insert that created <p> after the current <a> element:
}).insertAfter(this);
// filtering the childNodes of the current <a>:
$(this).contents().filter(function() {
// keeping only those that are of nodeType === 3
// and therefore are textNodes:
return this.nodeType === 3;
// removing those nodes:
}).remove();
});
$('li a').each(function() {
$('<p>', {
'text': this.textContent
}).insertAfter(this);
$(this).contents().filter(function() {
return this.nodeType === 3;
}).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a href="/">
<img src="http://lorempixel.com/300/300/people" />text to be converted to element</a>
</li>
</ul>
参考文献:
- JavaScript:
Node.nodeType
Node.textContent
- jQuery:
contents()
each()
filter()
wrap()
使用.html()
var someText = 'Hey!';
$('#test').html('<p>' + someText + '</p>');
Fiddle:http://jsfiddle.net/howderek/3t3Lw75x/
相关文章:
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 将JSON插入MongoDB中,自动转换字符串中的日期
- 以点表示法转换字符串以获取对象引用
- 在 JavaScript 中转换字符串 11/28/2014 11:00 AM 到现在
- 为什么在主干的字符串数组中转换字符串数组
- 如何简单地转换字符串
- AngularJS如何转换字符串“;yyyyMMdd”;迄今为止
- 如何防止htmlspecialchar(PHP)转换字符串中的整数
- 刷新Aurelia中的i18n转换字符串插值
- 发布时禁用转换字符串
- 转换字符串货币
- 在javascript ajax调用中转换字符串到数组
- 转换字符串包含时间到24小时的时间,我可以做数学与- jQuery
- IE javascript引擎在转换字符串到日期时呈现NaN
- 如何转换字符串“a,b,c,d……”成a.b (c, d . .);来执行
- 如何在javascript中转换字符串到日期格式
- 如何在嵌套数组中转换字符串数组
- 在javascript中转换字符串日期
- 转换字符串在印度格式的javascript
- Javascript转换字符串到数组的对象