简体   繁体   English

如果检查收音机,如何替换ap标签值?

[英]How to replace a p tag value if a radio is checked?

I want replace ap tag value if a radio is checked. 如果选中了收音机,我想要替换ap标签值。

I write some JS to do this,but nothing changed. 我写了一些JS来做这件事,但没有改变。 this is my code(I use jquery) 这是我的代码(我使用jquery)

<script>
$(function(){
if ($('#A:checked')) {
   $("#change_me").html('<input type="radio" value="1" name="fruit">')
 }

if ($('#B:checked')) {
   $("#change_me").html('<input type="radio" value="2" name="fruit">')
 }

}
</script>

<input type="radio" name="e" id="A" checked="checked">
<input type="radio" name="e" id="B">

<p id="change_me">
   <input type="radio" value="1" name="fruit">
</p>

Thanks. 谢谢。

The :checked selector matches elements that are currently checked. :checked选择器匹配当前检查的元素。
Writing $('#B:checked') returns a jQuery object containing either zero or one element. 编写$('#B:checked')返回一个包含零个或一个元素的jQuery对象。 It cannot be used directly as a condition. 它不能直接用作条件。

Instead, you can check if ($('#B:checked').length) to see whether the jQuery object has anything in it. 相反,您可以检查if ($('#B:checked').length)以查看jQuery对象中是否包含任何内容。

First, you don't need to recreate the radio button if only the value is changing. 首先,如果只有值发生变化,则无需重新创建单选按钮。

$(function(){
if ($('#A:checked').size() > 0) {
   $("#change_me input[type=radio]").val('1')
 }

if ($('#B:checked').size() > 0) {
   $("#change_me input[type=radio]").val('2')
 }

}

HTML: HTML:

<input type="radio" name="e" id="A" checked="checked">
<input type="radio" name="e" id="B">

<p id="change_me">
   <input type="radio" value="1" name="fruit">
</p>

Replace the JavaScript code you have with the following 以下内容替换您拥有的JavaScript代码

$(function(){
    $('input[name=e]').change(function(){
        if($(this).attr('id') == 'A')
        {
            $("#change_me input").val('1');
        }
        else
        {
            $("#change_me input").val('2');
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM