javascript - 通过选中单选按钮更改链接

标签 javascript html css

我必须修改<meta property="og:url" content="http://a42de5e.contato.site/agradecimento"> <- 当有人在单选按钮中选中"is"时,有什么方法可以使用 JavaScript 完成吗?

<div class="form-group">

  <h4 class="control-label" data-selector="h4">Would you support us?</h4>

  <label class="radio-inline"><input type="radio" name="Yes" value="Yes">Sim</label>
  <label class="radio-inline"><input type="radio" name="No" value="No ">Não</label>

</div>

我尝试使用“getElementByID”,但我不确定是否可行,因为它是元标记

最佳答案

通过给指定的 meta 标签一个 IDinput[type="checkbox"] 元素一个 ID 你可以实现你的目标。

在我的回答中,meta 标签的内容是根据 input[type="checkbox"] 状态设置的:如果选中,则新 url 设置为content 属性,否则,如果未选中,我们将返回到 meta 标记的初始内容。

In the snippet I gave an id="opengraph" to the meta tag, and an id="toggle" to the input[type="checkbox"].

// declaring  variables so we make our task easier.

/**
* referencing the 'meta' tag by the 'og' variable.
* referencing the 'checkbox' tag by the 'toggle' variable.
* the 'oldOG' variable stores the initial content of the 'meta' tag, so when the 'checkbox' gets unchecked the initial content is set to the 'meta' tag.
* the 'newOG' variable stores the new content(url), change it per your requirements.
**/
var og = document.getElementById('opengraph'),
    toggle = document.getElementById('toggle'),
    oldOG = og.getAttribute('content'),
    newOG = 'add your new link here';
// adding a change event listener to the 'checkbox', and alter the content of the 'meta' tag based on the 'checkbox' state(if checked => newOG is set, if unchecked => the initial content(oldOG) is set).
toggle.addEventListener('change', function() {
  og.setAttribute('content', (this.checked === true) ? newOG:oldOG);
  
  // just for the demo, remove the next line in production phase.
  console.log('content: ' + og.getAttribute('content'));
});
<meta id="opengraph" property="og:url" content="http://a42de5e.contato.site/agradecimento">
<span>toggle the meta tag's content<input type="checkbox" id="toggle" /></span>

这里有一些有用的链接:

Learn more about addEventListener method.

Learn more about the change event.

Learn more about getElementById method.

Learn more about getAttribute method.

Learn more about setAttribute method.

希望我能进一步插入你。

关于javascript - 通过选中单选按钮更改链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52303286/

相关文章:

javascript - bootstrap 3 datetimepicker 自定义年份

javascript - 页面的打印版本。我想附加相关链接的完整网址

javascript - Highcharts 饼图数据格式

javascript - 在运行剩余的 javascript 之前检查有效的电子邮件

javascript - 样式范围属性

html - 背景不透明度扩展

html - 如何更改数字文本框输入的高度

javascript - Jquery 代码不适用于密码确认

css - 如何构建带有渐变边框的范围 slider ?

css - 如何裁剪引导图像以获得所有图像的宽度 285 和高度 170?