[英]How to remove <br> and everything after that?
如果我这样做,以下是好的:
<div id="results">
<p>Hello<br>there</p>
</div>
$($("#results p").children('br').get(0).nextSibling).remove();
我明白了: hello
但如果我这样做:
<th class="infobox">Head</th>
<td>Hello<br>there</td>
var newLineRemove = $(".infobox td").children('br').get(0).nextSibling();
$wikiDOM.find(newLineRemove).remove();
给我
未捕获的TypeError:无法读取未定义的属性“nextSibling”
那是因为.get(...)
返回一个DOM元素而不是一个jQuery对象。 在第一个示例中,您使用$(...)
将该DOM元素转换为jQuery对象,但在第二个示例中您没有这样做。
这会将DOM元素转换为jQuery元素并消除错误
var newLineRemove = $($(".infobox td").children('br').get(0).nextSibling);
但它不会做你想做的事,因为@ Forty3说“ <td>
不在..infobox里面”
这似乎有效,但我可能会让事情变得更复杂,然后他们必须:
$(function(){ var td = $(".infobox").next(); if(td.find("br").length){ $(td.contents().get().reverse()).each(function(){ $(this).remove(); if(this.tagName == "BR"){ return false; } }); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <th class="infobox"></th> <td>Hello<br>there</td> </table>
我是最简单的解决方案,试试这个:
$('td').each(function() { $(this).html($(this).html().split('<br>')[0]); });
li { margin-bottom: 10px; } #usp-custom-3 { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table> <tr> <th class="infobox"></th> </tr> <tr> <td>Hell <br>there</td> </tr> <tr> <td>Hello <br>there<br>there</td> </tr> </table>
您的代码不起作用,因为".infobox td"
选择是寻找内部的TD元素.infobox
元素,但在你的HTML的TD紧随.infobox
。
如果你想要的东西与你现有的JS非常相似但是使用那个HTML(注意td和th元素需要在表中的tr中)你可以这样做:
$($(".infobox").next().children("br")[0].nextSibling).remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <th class="infobox"></th> <td>Hello<br>there</td> </tr> </table>
也就是说,使用.next()
获取.infobox
之后的.infobox
,获取该元素的子br元素,获取第一个.nextSibling
,然后将其包装在jQuery对象中,以便可以调用.remove()
。
编辑:请注意,如果有多个具有相似元素的行,则上述代码仅在第一个代码上执行删除操作。 如果是我的代码,我可能会选择所有相关元素,然后更新他们的HTML更像这样:
$(".infobox").next("td").html(function(i, h) { return h.split('<br>')[0] })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.