Javascript 替换所有div和p中的某个短语,并添加图像作为背景
我想使用javascript将“hellokitty”这样的短语替换为“Hellocate”,并为包含html代码中所有Javascript 替换所有div和p中的某个短语,并添加图像作为背景,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我想使用javascript将“hellokitty”这样的短语替换为“Hellocate”,并为包含html代码中所有和标记中的“hello”的标记添加背景 我尝试了以下方法,但不起作用 <html> <head> </head> <body> <div>hellokitty!</div> <p>hellokitty!</p> <div>hellokitty!&l
和
标记中的“hello”的标记添加背景
我尝试了以下方法,但不起作用
<html>
<head>
</head>
<body>
<div>hellokitty!</div>
<p>hellokitty!</p>
<div>hellokitty!</div>
<p>hellookitty</p>
<span>hellokitty!</span>
<script>
document.getElementsByTag("div")[0].style.backgroundImage = "url('https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx')";
document.body.innerHTML =document.getElementsByTag("div")[0].innerHTML.replace(/I hate forest!/g, 'I love forest!');
</script>
</body>
</html>
你好!
你好
你好!
hellookitty
你好!
document.getElementsByTag(“div”)[0].style.backgroundImage=“url('https://www.royalcanin.com/~/media/Royal Canin/Product Categories/cat成人登陆英雄.ashx');
document.body.innerHTML=document.getElementsByTag(“div”)[0].innerHTML.replace(/I hate forest!/g,'I love forest!');
它不起作用我使用了Jquery,所以我不知道它是否能帮助您,但这里是我的解决方案:
$.each($("body").find("div, p"), function(k, v) {
$this = $(this);
$this.text( $this.text().replace("hellokitty", "hellocat") );
if ($this.text().match("hello")) {
$this.css("background-image", "url('paper.gif')");
}
})
实时版本(我将背景图像更改为彩色,因为我无法在JSFIDLE上加载图像)。是的,这是完全可能的 让我们看看您正在尝试做什么:
和
。为此,我们可以使用document.querySelectorAll()
String.prototype.replace()
Element.style.background
//选择页面上的所有div和p元素。这将返回一个类似列表的对象,称为HTMLCollection
var元素=document.queryselectoral(“div,p”);
//循环返回的HTMLCollection
对于(var i=0;i
应更换这些事件
这是一些hellokitty的文本,还有一些
你好
我们正在替换html,以便保留hellokitty样式标记等
这些都不应该被取代
我和hellokitten这个短语不匹配
我是span
,而不是div
或p
。你好
div
不是ID…它是元素类型。如果要使用getElementById(“您的ID”)
@Charlotte45I,则需要在div
上添加ID
。我试着使用by标记,只尝试了第一次,但仍然不起作用…getElementsByTagName
,而不是getElementsByTag
OP出于某种原因使用了jQuery
标记,所以我想你的答案是相关的。为什么要筛选。is(“div”)
<代码>p也应该有背景。另外,通过缓存$this=$(this)
一次来优化您的代码,而不是每次都重新包装$(this)
。我错过了阅读,我以为它只是有背景的div,不管怎样,我只是按照您所说的进行了编辑,谢谢!那就让我投票吧:)