簡體   English   中英

單選按鈕值未傳遞到jquery中的發布函數

[英]Radio button value didn't passed to post function in jquery

我想通過單選按鈕(例如,性別是男性還是女性)獲得價值。 我將其存儲在value變量中,但同時將其傳遞給$ .post卻不起作用? 該代碼段是-

$(document).ready(function() {
  // Handler for .ready() called.

  $("input:radio[name=gender]").click(function() {
    var value = $(this).val();
    alert (value);
  });
  alert (value);
  $.post("gendersearch.php", {queryString: ""+value+""}, function(data) { // Do an AJAX call
    $('#suggestions').fadeIn(); // Show the suggestions box
    $('#suggestions').html(data); // Fill the suggestions box
  });

});

如何糾正? 問題是什么。

$("input:radio[name=gender]").click(function() {
        var value = $(this).val();
        alert (value);
    });
      alert (value);

請檢查變量value的范圍,在外部定義它,然后嘗試這樣

var value = '';
  $("input:radio[name=gender]").click(function() {
            value = $(this).val();
            alert (value);
  });
  alert (value);

value變量放在click事件之外。

$(document).ready(function() {
    // Handler for .ready() called.
    var value = "";
    $("input:radio[name=gender]").click(function() {
        value = $(this).val();
        alert(value);
    });
    alert(value);
    $.post("gendersearch.php", {
        queryString: "" + value + ""
    }, function(data) { // Do an AJAX call
        $('#suggestions').fadeIn(); // Show the suggestions box
        $('#suggestions').html(data); // Fill the suggestions box
    });
});

如建議的那樣,您可以通過兩種方式執行此操作-

第一

聲明的var value = ''; 就在您的點擊功能上方,就像下面的代碼一樣

$(document).ready(function() {
  // Handler for .ready() called.
   var value="";
  $("input:radio[name=gender]").click(function() {
   value = $(this).val();
    alert (value);
  });
  alert (value);
  $.post("gendersearch.php", {queryString: ""+value+""}, function(data) { // Do an AJAX call
    $('#suggestions').fadeIn(); // Show the suggestions box
    $('#suggestions').html(data); // Fill the suggestions box
  });

});

第二

另一種方法是在click函數中聲明post方法

    $(document).ready(function() {
      // Handler for .ready() called.

      $("input:radio[name=gender]").click(function() {
        var value = $(this).val();
        alert (value);
 $.post("gendersearch.php", {queryString: ""+value+""}, function(data) { // Do an AJAX call
        $('#suggestions').fadeIn(); // Show the suggestions box
        $('#suggestions').html(data); // Fill the suggestions box
      });
      });
      //alert (value);
    });

好吧,我認為這是雙向的。 但是第一個更輕松! 更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM