我想突出显示文字的前10个字符以及单词“段落”的颜色出现。如何使用Javascript或jQuery突出显示文本的前10个字符?
<html>
<body>
This is a heading
This is a paragraph.This is another paragraph.
</body>
</html>
我想突出显示文字的前10个字符以及单词“段落”的颜色出现。如何使用Javascript或jQuery突出显示文本的前10个字符?
<html>
<body>
This is a heading
This is a paragraph.This is another paragraph.
</body>
</html>
考虑到这是你的HTML内容:
<div id="contents">
This is a heading
This is a paragraph.This is another paragraph.
</div>
这jQuery代码会做你想要的是什么:
$(document).ready(function() {
var data = $('#contents').text().trim();
var str = "";
for(var i = 0; i < 10; i++) {
str += data[i];
}
data = data.replace(/paragraph/g, '<span style="font-weight: bold;">paragraph</span>');
data = data.replace(str, '<span style="background-color: yellow;">' + str + '</span>');
$('#contents').html(data);
});
您的代码不会转义内容 – 2012-07-22 06:27:38
这只是一个快速回复。当然你可以改进。 – 2012-07-22 06:29:18
@MuhammadAhmadZafar它没有工作 – 2012-07-22 13:50:41
尝试在JS这个代码。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to highlight.</p>
<p id="demo">This is a heading. This is a paragraph. This is another paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
var str= document.getElementById("demo").innerHTML;
var str1 = "";
for(var i = 0; i < 10; i++) {
str1 += str[i];
}
var n=str.replace(str1,'<span style="font-weight: bold;">' + str1 + '</span>');
document.getElementById("demo").innerHTML=n;
}
</script>
</body>
</html>
您错过了**段**部分。但至少尝试了一种不同的逻辑。 – 2012-08-10 06:37:20
What.Have.You.Tried.com – dda 2012-07-22 06:05:33
做空间/新线算作字符,或者你需要分析那些出来,抢其他有效字符? ie:是吗?“这是一个”或者它是什么“”这是一个hea“? 另外 - 突出显示有什么特殊要求吗?它可以在JS中完成吗?它是否需要在服务器端完成?你能把它写在原地吗?因为你可以去:'这是一个'并计算出10个字符 - 然后编辑'.highlight' CSS属性 - 或者只使用'html5'标签。 – Norguard 2012-07-22 06:07:19
@Rajeev我的答案对你有帮助吗? – 2012-07-22 07:12:02