我正在尝试默认选择第一个单选按钮。但是,我尝试过的每个代码都不起作用。任何帮助将不胜感激。
jsfiddle - http://jsfiddle.net/te2b5dqy/
$('.radiogroup').change(function(e) {
const $this = $(this), $link = $("#url");
$link.html($this.val());
$link.attr("href", $this.attr("data-url"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="radiogroup" id="radiogroup1" class="radiogroup" value="Google" data-url="https://google.com" />
<input type="radio" name="radiogroup" id="radiogroup2" class="radiogroup" value="Bing" data-url="https://www.bing.com/" />
<a id="url" href="" target="_blank">null</a>
最佳答案
您只需添加.eq(0).click()
$('.radiogroup').change(function(e) {
const $this = $(this), $link = $("#url");
$link.html($this.val());
$link.attr("href", $this.attr("data-url"));
}).eq(0).click(); //<<<<<<< here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="radiogroup" id="radiogroup1" class="radiogroup" value="Google" data-url="https://google.com" />
<input type="radio" name="radiogroup" id="radiogroup2" class="radiogroup" value="Bing" data-url="https://www.bing.com/" />
<a id="url" href="" target="_blank">null</a>
或 .eq(0).prop('checked' , true).change()
$('.radiogroup').change(function(e) {
const $this = $(this), $link = $("#url");
$link.html($this.val());
$link.attr("href", $this.attr("data-url"));
}).eq(0).prop("checked" , true).change(); //<<<<<<< here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="radiogroup" id="radiogroup1" class="radiogroup" value="Google" data-url="https://google.com" />
<input type="radio" name="radiogroup" id="radiogroup2" class="radiogroup" value="Bing" data-url="https://www.bing.com/" />
<a id="url" href="" target="_blank">null</a>
附加:有很多方法可以选择第一个单选 .eq(0)
、 .first()
、 。 filter(':eq(0)')
, .filter(':nth-child(1)')
关于javascript - 默认选择第一个单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981650/