繁体   English   中英

jQuery单选按钮单击和更改功能不起作用

[英]jquery radio button click and change function not working

我想根据单选按钮的值隐藏和显示div。 HTML代码是

<div id="share_to_others">
  <input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type">
  <input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type">
  <input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type">
</div>

我尝试过的jQuery代码是

$("#share_to_others input[name='fx_sharepl_type']").click(function () {
    alert("test");
});

$("#share_to_others input[name='fx_sharepl_type']").change(function () {
    alert("test");
});

$("#fx_sharepl_type").change(function () {
    alert("asdas");
});

$("input[name=fx_sharepl_type]:radio").change(function () {
    alert("click fired");   
});

$(document).on('change', 'input:radio[name=fx_sharepl_type"]', function (event) {
    alert("click fired");
});

其中许多来自jsfiddle的工作演示,但不是为我工作,我不知道为什么。 我做错什么了吗?

您必须为每个单选按钮提供唯一的ID,然后再按照这种方式进行操作。

$("#r1, #r2, #r3").change(function () {

在此处输入图片说明 您的代码很麻烦,但是您忘记在JSFiddle窗口的左侧包含一个JQuery源版本。 选择任何版本的JQuery将使您的代码正常工作。

 $(function() { // DOM loaded event handler var show_duration = 0; var content_33 = $("#content_33"); var content_22 = $("#content_22"); var content_11 = $("#content_11"); var bloc_radio_share = $("#share_to_others"); // Take an html element in parameter and show it function show_content(content_id) { content_id.show(show_duration); } // Take an html element in parameter and hide it function hide_content(content_id) { content_id.hide(0); } hide_content(content_22); hide_content(content_11); bloc_radio_share.change(function() { var radio_checked_val = $('input[name=fx_sharepl_type]:checked', '#share_to_others').val(); if (radio_checked_val == 33) { hide_content(content_22); hide_content(content_11); show_content(content_33); } else if (radio_checked_val == 22) { hide_content(content_33); hide_content(content_11); show_content(content_22); } else { // case content == 11 hide_content(content_33); hide_content(content_22); show_content(content_11); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="share_to_others"> <label> <input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type" checked /> 33 </label> <label> <input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type" /> 22 </label> <label> <input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type" /> 11 </label> </div> <div id="content_33"> This div is displayed because of click on radio button 33 </div> <div id="content_22"> Radio button 22 has been clicked so I appear </div> <div id="content_11"> If you click on radio button 11 you'll see me, like now </div> 

这是适合您的算法示例。 逻辑可能不是最好或最快的,但这只是一个开始。

暂无
暂无

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

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