如何使用单击单选按钮更改链接的多个属性

How to change multiple attributes of a link using onclick of radio button?

本文关键字:属性 链接 何使用 单击 单选按钮      更新时间:2023-09-26

我一直在尝试使用单选按钮的onclick属性来更改链接的多个属性。但它不起作用。我是Javascript的新手,所以任何帮助都将不胜感激。到目前为止,这是我的代码。

<input type="radio" name="test" onclick="setAttributes(document.getElementById('submit'), {"class": "first", "href": "http://www.google.com"});">First<br/>
<input type="radio" name="test" onclick="setAttributes(document.getElementById('submit'), {"class": "second", "href": "http://www.stackoverflow.com"});">Second<br/>
<a id="submit" class="" href="">Click Here</a>
<script>
    function setAttributes(el, attrs) {
        for(var key in attrs) {
            el.setAttribute(key, attrs[key]);
        }
    }
</script>

请参阅此演示

<input type="radio" name="test" onclick="setAttributes(document.getElementById('submit'), {'class': 'first', 'href': 'http://www.google.com'});">First<br/>
<input type="radio" name="test" onclick="setAttributes(document.getElementById('submit'), {'class': 'second', 'href': 'http://www.stackoverflow.com'});">Second<br/>
<a id="submit" class="" href="">Click Here</a>

您传递的参数有"'字符(引号(错误。

JS代码将是

<script>
function setAttributes(el) {
    for(var key=1;k<arguments.length;k++) {
        el.setAttribute(arguments[k], arguments[k+1]);
        k++;
    }
}
</script>

HTML将是

<input type="radio" name="test" onclick="setAttributes(document.getElementById('submit'), "class", "first", "href" "http://www.google.com");">First<br/>

只需在onclick="…"中用单个'更改"

<input type="radio" name="test" onclick="setAttributes(document.getElementById('submit'), {'class': 'first', 'href': 'http://www.google.com'});">First<br/>
<input type="radio" name="test" onclick="setAttributes(document.getElementById('submit'), {'class': 'second', 'href': 'http://www.stackoverflow.com'});">Second<br/>
<a id="submit" class="" href="">Click Here</a>

JAVASCRIPT

function setAttributes(el, attrs) {
        for(var key in attrs) {
            el.setAttribute(key, attrs[key]);
        }
    }

DEMO