【问题标题】:Adding jquery onchange effect on select values returned by ajax对ajax返回的选择值添加jquery onchange效果
【发布时间】:2015-09-25 23:48:58
【问题描述】:

好的,我有一个从数据库返回值的组合框。这一切都是通过 ajax 发生的。用户可以单击一个名为添加新行的按钮,将生成一个新行,该行也将由一个组合框提供支持。 但是,我需要将“onchange”事件附加到 ajax 返回的组合框。

我试过了:-

<script type="text/javascript">
$('.combobox').change(function() {
  var va = $('.combobox').val();
  alert(va);
});
</script>

但这没有用。我无法收到有关 onchange 事件的任何警报。

我必须尝试什么?
这是我的 ajax :-

try
{
  $s = $conn->query("SELECT * FROM testing2");
}
catch(PDOException $e)
{
  echo $e->getMessage();
}

$selectBegin = "";
$selectBegin = 
  '
  <select class="combobox">
    <option value=""></option>
    ';
    $innerSelectString = "";
$selectMain = "";
while($customers = $s->fetch(PDO::FETCH_OBJ))
{
  //fix the select thing here
  $si = "<option value='$customers->indexid'>$customers->v1</option>";
  $selectMain .= $si;
}
$selectEnd = '</select>';
$selectFinal = $selectBegin . $selectMain . $selectEnd;
return $selectFinal;

有多个组合框,我有这个 jquery 代码来运行组合框:-

function load_content_rows()
{
  $(document).ready(function() {
    $.ajax({    //create an ajax request to load_page.php
      type: "GET",
      url: "ajax.php?requestid=1",             
      dataType: "html",   //expect html to be returned                
      success: function(response){                    
        $("#requestMaker").html(response); 
        $("#requestMaker").find(".combobox").combobox();
        //alert(response);
      }
    }); //ajax request end
  });
} //load_content
load_content_rows();

如何将 onchange 事件添加到我的所有组合框? 这是它们的外观:-

【问题讨论】:

    标签: javascript jquery ajax combobox


    【解决方案1】:

    从 AJAX 选项中删除这部分,这可能会节省很多问题:

    dataType: "html",   //expect html to be returned
    

    所以你的 AJAX 请求应该是这样的:

    $(document).ready(function() {
      function load_content_rows() {
        $.ajax({                        //create an ajax request to load_page.php
          type: "GET",
          url: "ajax.php?requestid=1",             
          success: function(response){                    
            $("#requestMaker").html(response); 
            $("#requestMaker").find(".combobox").combobox();
                                        // alert(response);
          }
        });                             // ajax request end
      }                                 //load_content
      load_content_rows();
    });
    

    【讨论】:

    • @Akshay 你能做一个完整的小提琴吗?另外,您能否检查一下控制台中发生了什么?
    • 好的,正在学习小提琴。但是,php代码也包括在内。
    • 尝试创建 plunk 并将 PHP 响应包含为 HTML 文件并请求 hte HTML。
    • 好的,给我 5 分钟。
    • @Akshay 如果没有 DB 和正确设置,就无法调试吧?
    【解决方案2】:

    我真的想不出任何可以阻止.change() 处理&lt;select&gt; 元素的事情,但我没有看到您在调用ajax 后替换和重新创建组合框后绑定事件。这是一个新元素,因此需要再次绑定。在调用.combobox() 后,在成功函数中添加您的.change,看看是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      相关资源
      最近更新 更多