gpt4 book ai didi

javascript - 使用 Javascript 更改 CSS 元素

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:17 26 4
gpt4 key购买 nike

使用 javascript,我试图在输入特定 url 参数时更改 div 类的背景图像。但是,它不会在后台切换图像。

示例网址:

 example.com?campaignid=street

HTML

<div class="row-background-79134">
<p>Some content here</p>
</div>

脚本在这里:

<script>
function getQueryParams(qs) {
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}

var query = getQueryParams(document.location.search);
var myCampaign = query.campaignid;


if (myCampaign == "street"){
var elems = document.getElementsByClassName('row-background-79134');
for(var i = 0; i < elems.length; i++) {
elems[i].style.background = 'url(https://example.com/image1.jpg) no-repeat center center;'
}

if (myCampaign == "plumber"){
var elems = document.getElementsByClassName('row-background-79134');
for(var i = 0; i < elems.length; i++) {
elems[i].style.background = 'url(https://example.com/image2.jpg) no-repeat center center;'
}

if (myCampaign == "cowboy"){
var elems = document.getElementsByClassName('row-background-79134');
for(var i = 0; i < elems.length; i++) {
elems[i].style.background = 'url(https://example.com/image3.jpg) no-repeat center center;'
}

if (myCampaign == "hairdresser"){
var elems = document.getElementsByClassName('row-background-79134');
for(var i = 0; i < elems.length; i++) {
elems[i].style.background = 'url(https://example.com/image4.jpg) no-repeat center center;'
}

</script>

在这方面的任何帮助都会很棒。

最佳答案

这些 block 中的每一个

if (myCampaign == "street"){
var elems = document.getElementsByClassName('row-background-79134');
for(var i = 0; i < elems.length; i++) {
elems[i].style.background = 'url(https://example.com/image1.jpg) no-repeat center center;'
}

应该用额外的大括号重写,像这样

if (myCampaign == "street"){
var elems = document.getElementsByClassName('row-background-79134');
for(var i = 0; i < elems.length; i++) {
elems[i].style.background = 'url(https://example.com/image1.jpg) no-repeat center center;';
} // added this
}

还可以考虑添加一些日志记录。使用 console.log 向您展示正在发生的事情,然后打开您的浏览器控制台以阅读输出。例如,您可能想知道 myCampaign 的值是多少。

console.log(myCampaign);

会有所帮助,靠近顶部。还有其他方法可以使代码更易于阅读/维护,但正确使用大括号应该是第一步。

关于javascript - 使用 Javascript 更改 CSS 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com