【问题标题】:Radio button onchange function not working if radio is checked directly by link parameter如果通过链接参数直接检查单选按钮,则单选按钮 onchange 功能不起作用
【发布时间】:2017-03-30 23:09:24
【问题描述】:

当我们点击一​​个单选按钮时,它会运行一个onchange jQuery 函数。但是,如果我们直接通过链接参数检查同一个单选按钮,则不会调用该函数。请问,这个怎么解决?我尝试将onchange 更改为onclick,但没有成功。

我正在处理的页面:一旦手动选择了任何 Store,onchange 函数将隐藏 Store DIV 并显示 Category DIV,模拟步进过滤器。 http://www.hotsales.com.br/procurar/

这是自动选择某个商店的直接链接参数。但这样一来,onchange 函数并没有运行,所以 Store DIV 仍然可见,Category DIV 仍然隐藏。 http://www.hotsales.com.br/procurar/?offer_store=852

这是在选择 Store 时应该运行的第一个函数(手动或通过直接链接)。

/* AJAX SEARCH*/
$(document).on( 'change', '.advanced-search input', function(){

start_ajax_search3();

    $.ajax({
        url: $('.advanced-search').attr('action'),
        data: $('.advanced-search').serialize(),
        success: function( response ){
            handle_ajax_search_response( response ); /*this function hide/show desired DIV*/
        },
        complete: function(){
            end_ajax_search();
        }
    });
});

这是隐藏/显示 DIV 的方式:

function handle_ajax_search_response( response ){
    var $response = $('<div>'+response+'</div>');
    $('.ajax-results').html( $response.find('.ajax-results').html() );
    $('.ajax-sidebar').html( $response.find('.ajax-sidebar').html() );
    $('.category-filter').show();
    $('.store-filter').hide();
    $('.offer-type-filter').show();}

【问题讨论】:

  • 通过链接参数检查复选框的内容是什么?后端?
  • 只要让它在页面加载时调用相关单选按钮上的.click()
  • @Panomosh 但要检查的条件不是页面加载,而是 url 中的参数。这个想法很好,但您必须根据您所说的参数有条件地调用该脚本。如果服务器观察到该参数和检查,那么在加载时运行 click callbaclk 的包含的脚本应该也是如此。
  • 谢谢大家!亚历山德罗的建议对我有用。

标签: javascript jquery html


【解决方案1】:

您可以在 change 和文档 ready 上调用您的函数,例如:

function test(chk){
  console.log("called by" + $(chk).attr("id"));
}

$(document).ready(function(){
  if($("#chkTest2").is(":checked")){
    test($("#chkTest2"));
  }
});

$(".chkboxes").on( 'change', function(){
  test(this);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="chkboxes" type="checkbox" id="chkTest1">Test 1
<input class="chkboxes" type="checkbox" id="chkTest2" checked="checked"> Test 2

希望对你有帮助,再见。

【讨论】:

  • 这是我的改编代码:$(document).ready(function(){ if($('input[id^=offer_store_]').is(":checked")){ $('.store-filter').hide(); $('.category-filter').show(); $('.offer-type-filter').show(); } });上帝保佑你!
  • 我使用'input[id^=offer_store_]' 作为通配符 ID 选择器。因此,它适用于以offer_store_ 开头的每个商店 ID,例如 offer_store_1507、offer_store_852 等。完美!
  • 很高兴它对您有所帮助。再见。
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
相关资源
最近更新 更多