如果文本块中包含一个特定的字符串,使用jQuery删除第一行
Remove first line from a Text block if it contains a specific string - using jQuery
我有一个表,其中有一些内容。并非所有行都有相同的内容,但其中一些行的第一句话如下:
你好,约翰,你好吗?
你好,玛丽,你好吗?
相同的模式,不同的名称。
该行看起来如下所示。跨度中的内容来自数据库。是的,文本也有换行标签。
<tr style="background-color:#F7F7f7">
<td>
<span id="sp1">Hello How Are you? John <br/><br/>Some text blalablalalbal <br/><br/>"You are Awesome" <br/><br/>----What can I do for you? <br/><br/></span><br />
<span id="sp2">XYZABCD</span><br />
<span id="sp3">12345669060 Some Loren ipsum</span><br />
</td>
</tr>
我想从包含的行中删除第一句话.
所以我有下面的代码,工作和做我想要的:
<script type="text/javascript">
$(function () {
$("#btnCleanUp").click(function () {
$("table tr td").each(function () {
var elem = $(this).find('span:contains("Hello How Are you?")');
var alltxts = elem.contents().filter(function () {
var retm = true;
var str = this.nodeValue;
if (str != null) {
var bstr = str.indexOf("Hello How Are you?");
$(this).nodeValue = "";
if (bstr >= 0) {
retm = false;
}
}
var ret = (this.nodeType == 3) && retm;
return ret;
});
elem.text("");
elem.html("<br/>");
$(alltxts).each(function () {
var hm = $(this);
elem.html(elem.html() + hm[0].nodeValue + "<br/><br/>");
});
});
});
});
</script>
下面是示例演示。
问题:
我可以用更好的方式做这件事吗?
如果可能的话,我想简化上面的代码块,我的意思是逻辑上的,因为我认为考虑到jquery的潜力,它可以以更好的方式完成。
如果c#是更好的方法,我愿意用c#来做这个。请提供示例代码$(function () {
$("#btnCleanUp").click(function () {
$("table tr td span").each(function () {
var data = $(this).html();
data = data.replace(/^Hello how are you'?.*?(<br ?'/?>){1,2}/i,'');
$(this).html(data);
});
});
});
查看demo
但我不确定JavaScript是最好的地方做这个
你可以去掉那个$.each
循环:
$(function() {
$("#btnCleanUp").click(function() {
var elm = $("table tr td").find('span:contains("Hello How Are you?")');
var alltxts = elm.contents().filter(function() {
var retm = true;
var str = this.nodeValue;
if (str != null) {
var bstr = str.indexOf("Hello How Are you?");
$(this).nodeValue = "";
if (bstr >= 0) {
retm = false;
}
}
var ret = (this.nodeType == 3) && retm;
return ret;
});
elm.text("");
elm.html("<br/>");
$(alltxts).each(function() {
var hm = $(this);
elm.html(elm.html() + hm[0].nodeValue + "<br/><br/>");
});
});
});
小提琴:http://jsfiddle.net/maniator/ZDx4x/12/
相关文章:
- 如何在不删除类似侦听器的情况下从父对象中删除jQuery事件侦听器
- 如何比较两个字符串并删除jquery中的元素
- 从此代码中删除 Jquery
- 删除jQuery添加的按钮
- 如何删除jQuery.haverage()方法中的延迟
- 如何删除jQuery组中其他成员的后代元素
- 删除jQuery中的事件不起作用
- 添加和删除jquery-li元素
- 如何删除jquery可拖动项的子项
- 如何编辑和删除jQuery数据表的每一行
- 使用滑动存储cookie以删除jquery mobile
- 如何从 HTML 元素中停止或删除 jQuery 函数
- 如何删除 jquery 可折叠数据角色=“可折叠”
- 删除 Jquery/Javascript 对象中的字符
- 删除 jQuery 上的内容
- 从数据表中删除 jquery MVC5
- 查找文本并将其删除 jquery
- 动态预置和删除 JQuery/JavaScript
- 更改父选择框时如何删除 Jquery 中的旧选项
- 删除 jQuery 中的数组元素