javascript 声明一个变量并在html中使用它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55123762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declare a variable and use it in html
提问by vasilis smyrnios
I have big html document with various images with href and src.
我有带有 href 和 src 的各种图像的大 html 文档。
I want to declare their href and src so as to change only their var values. something like...
我想声明它们的 href 和 src 以便仅更改它们的 var 值。就像是...
<script>
var imagehref = www.url.com;
var imagesrc = www.url.com/img.pg;
</script>
HTML Part:
<html>
<a href=imagehref><img src=imagesrc /> </a>
</html>
What is the correct syntax/way to do it?
什么是正确的语法/方法?
采纳答案by Luca Pierfederici
You can't do it in this way, you have to set href and src directly from the js script. Here's an example:
这种方式不行,必须直接从js脚本中设置href和src。下面是一个例子:
<html>
<body>
<a id="dynamicLink" href=""><img id="dynamicImg" src="" /> </a>
</body>
<script>
var link = document.getElementById('dynamicLink');
link.href = "http://www.url.com"
var img = document.getElementById('dynamicImg');
img.src = "http://www.url.com/img.png"
</script>
</html>
回答by brk
Add an identifier tot the anchor tag , then use setAttributeto set the hrefand src
将标识符添加到锚标记,然后用于setAttribute设置href和src
var imagehref = 'www.url.com';
var imagesrc = 'www.url.com/img.pg';
let anchor = document.getElementById('test');
anchor.setAttribute('href', imagehref);
anchor.querySelector('img').setAttribute('src', imagesrc)
<a id='test' href=''><img src='' /></a>
回答by AlexOwl
const imagehref = "https://google.com";
const imagesrc = "https://media3.giphy.com/media/sIIhZliB2McAo/giphy.gif";
function update(className, property, value) {
Array.from(document.getElementsByClassName(className)).forEach(elem => (elem[property] = value))
}
update("imagehref", "href", imagehref)
update("imagesrc", "src", imagesrc)
<a class="imagehref"><img class="imagesrc" /> </a>
<a class="imagehref"><img class="imagesrc" /> </a>
<a class="imagehref"><img class="imagesrc" /> </a>

