Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 基于另一个选择选择使用php不工作_Javascript_Php_Jquery - Fatal编程技术网

Javascript 基于另一个选择选择使用php不工作

Javascript 基于另一个选择选择使用php不工作,javascript,php,jquery,Javascript,Php,Jquery,Select基于另一个Select使用PHP仅在添加新行时不工作 有关演示,请访问(请参阅演示步骤) 加载页面时有两行,它们按需要工作。(服务选项与项目选项一致) 单击添加行按钮,将再添加一行 新插入的行不工作。(服务选择未提供任何选项,如前两个选项) 我尝试的是: <?php require_once '../home.php' ?> <?php if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_

Select
基于另一个
Select
使用
PHP
仅在添加新行时不工作

有关演示,请访问(请参阅演示步骤)

  • 加载页面时有两行,它们按需要工作。(服务选项与项目选项一致)
  • 单击添加行按钮,将再添加一行
  • 新插入的行不工作。(服务选择未提供任何选项,如前两个选项)
  • 我尝试的是:

    <?php require_once '../home.php' ?>
    <?php
    
    
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
            ob_clean();
    
            $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
            $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
            if( $action && $id && !is_nan( $id ) ){
    
                $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
                $stmt->bindParam(':irn',$id);
                $stmt->execute();
                $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
                $stmtin->bindParam(':irn',$id);
                $stmtin->execute();
                $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );
    
                if( $stmt->rowCount() > 0 ){
                    echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
                     while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
                     }
                }
            }
            exit();
        }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type='text/javascript' charset='utf-8'>
                function ajax(m,u,p,c,o){
                    var xhr=new XMLHttpRequest();
                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                    };
    
                    var params=[];
                    for( var n in p )params.push(n+'='+p[n]);
    
                    switch( m.toLowerCase() ){
                        case 'post': p=params.join('&'); break;
                        case 'get': u+='?'+params.join('&'); p=null; break;
                    }
    
                    xhr.open( m.toUpperCase(), u, true );
                    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    xhr.send( p );
                }
                function createmenu(r,o,h){
                    o.menu.innerHTML=r;
                }
    
    
    
                function bindEvents(){
                    var oSelItem=document.querySelector('select[name="item1"]');
                    var oSelService=document.querySelector('select[name="service1"]');
                    oSelItem.onchange=function(e){
    
                        var method='post';
                        var url=location.href;
                        var params={
                            'action':'get_dependant_menu',
                            'id':this.options[ this.options.selectedIndex ].value
                        };
                        var opts={
                            menu:oSelService
                        };
                        ajax.call( this, method, url, params, createmenu, opts );
                    }.bind( oSelItem );
                }
                document.addEventListener( 'DOMContentLoaded', bindEvents,false );
            </script> 
    </head>
    <body>
    <form method="post" action="invoice_form.php" id="item_sel">
    
        <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
       <tr>
        <td colspan="3">
          <input type="text" name="customer" value="" placeholder="Customer Name">
        </td>
      </tr>
      <tr>
        <th>Item</th>
        <th>Service</th>
        <th>Qty</th>
    
      </tr>
    
        <tr>
          <td>
          <select name='item1' class='country'>
                <option value="Select Item">Select Item</option>
                <?php
    
                    //$sql='select * from `item` order by `Sr` asc;';
                    $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                    $stmt->execute();
    
                    if( $stmt->rowCount() > 0 ){
                        while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                            echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                        }
                    }
    
                ?>
    </select></td>
    
          <td><select class="country" name="service1">
    </select></td>
    <td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
        </tr>
        <tr>
          <td>
          <select name='item2' class='country'>
                <option>Select Item</option>
                <?php
    
    
                    $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                    $stmt->execute();
    
                    if( $stmt->rowCount() > 0 ){
                        while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                            echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                        }
                    }
    
                ?>
    </select></td>
    
          <td><select class="country" name="service2">
    </select></td>
    <td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
        </tr>
        <tr>
            <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
            <span class="glyphicon glyphicon-save"></span> &nbsp; Save
            </button>
            </td>
        </tr>
    </table>
        <input type="button" class="add-row" value="Add Row">
    </form>
    <div id="markup_model" class="hide">
      <table>
        <tr>
          <td>
            <select name="nameitem" class="country">
                        <option>Select Item</option>
                        <?php 
                            $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC "); 
                            $stmt->execute();
    
                            if( $stmt->rowCount() > 0 ){ 
                                while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){ 
                                    echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                                }
                            }   
                        ?>
                    </select>
          </td>
          <td>
            <select class="country" name="namewhat"></select>
          </td>
          <td>
            <input type="text" name="nameqty" value="" placeholder="Quantity" />
          </td>
        </tr>
      </table>
    </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
      var cont = 3
      var qty = "qty"
      var item = "item"
      var what = "service"
    
      $(".add-row").click(function() {
        var nameqty = qty + cont;
        var nameitem = item + cont;
        var namewhat = what + cont;
    
        var markup = $('#markup_model tbody');
    
        $(markup).find('.country:eq(0)').attr('name', nameitem);
        $(markup).find('.country:eq(1)').attr('name', namewhat);
        $(markup).find('input').attr('name', nameqty);
    
        $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));
    
        cont++;
      });
    });
    </script>
    <script type='text/javascript' charset='utf-8'>
                function ajax(m,u,p,c,o){
                    var xhr=new XMLHttpRequest();
                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                    };
    
                    var params=[];
                    for( var n in p )params.push(n+'='+p[n]);
    
                    switch( m.toLowerCase() ){
                        case 'post': p=params.join('&'); break;
                        case 'get': u+='?'+params.join('&'); p=null; break;
                    }
    
                    xhr.open( m.toUpperCase(), u, true );
                    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    xhr.send( p );
                }
                function createmenu(r,o,h){
                    o.menu.innerHTML=r;
                }
    
    
    
                function bindEvents(){
                    var oSelItem2=document.querySelector('select[name="item2"]');
                    var oSelService2=document.querySelector('select[name="service2"]');
                    oSelItem2.onchange=function(e){
    
                        var method='post';
                        var url=location.href;
                        var params={
                            'action':'get_dependant_menu',
                            'id':this.options[ this.options.selectedIndex ].value
                        };
                        var opts={
                            menu:oSelService2
                        };
                        ajax.call( this, method, url, params, createmenu, opts );
                    }.bind( oSelItem2 );
                }
                document.addEventListener( 'DOMContentLoaded', bindEvents,false );
            </script>
            <script type='text/javascript' charset='utf-8'>
                function ajax(m,u,p,c,o){
                    var xhr=new XMLHttpRequest();
                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                    };
    
                    var params=[];
                    for( var n in p )params.push(n+'='+p[n]);
    
                    switch( m.toLowerCase() ){
                        case 'post': p=params.join('&'); break;
                        case 'get': u+='?'+params.join('&'); p=null; break;
                    }
    
                    xhr.open( m.toUpperCase(), u, true );
                    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    xhr.send( p );
                }
                function createmenu(r,o,h){
                    o.menu.innerHTML=r;
                }
    
    
    
                function bindEvents(){
                    var oSelItem3=document.querySelector('select[name="item3"]');
                    var oSelService3=document.querySelector('select[name="service3"]');
                    oSelItem3.onchange=function(e){
    
                        var method='post';
                        var url=location.href;
                        var params={
                            'action':'get_dependant_menu',
                            'id':this.options[ this.options.selectedIndex ].value
                        };
                        var opts={
                            menu:oSelService3
                        };
                        ajax.call( this, method, url, params, createmenu, opts );
                    }.bind( oSelItem3 );
                }
                document.addEventListener( 'DOMContentLoaded', bindEvents,false );
            </script>
    
    </body>
    </html>
    
    
    
    您的问题是因为此错误-未捕获的TypeError:无法在第243行的HTMLDocument.bindEvents处将属性“onchange”设置为null。您可以在inspect元素中看到相同的情况。这是因为您正在为尚未添加的item3定义函数bindEvents。此外,这仅在添加单行的情况下有效。更改了您的逻辑并大量使用jquery。我已经注释掉了你代码中的php部分,并对其进行了硬编码。还创建了一个php文件,用于在选择框更改时发送ajax响应

        <?php // require_once '../home.php' ?>
        <?php
    
        foreach($_POST as $key => $val) {
            echo "$key => $val <br>";
        }
    
            if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
                echo "here <br>";
                ob_clean();
        //
        //        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        //        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
        //        if( $action && $id && !is_nan( $id ) ){
        //
        //            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
        //            $stmt->bindParam(':irn',$id);
        //            $stmt->execute();
        //            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
        //            $stmtin->bindParam(':irn',$id);
        //            $stmtin->execute();
        //            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );
        //
        //            if( $stmt->rowCount() > 0 ){
        //                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
        //                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
        //                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
        //                 }
        //            }
        //        }
                echo "<option value='Select Service'>Select Service (Pant)</option>";
                echo "<option value='12121211'>Iron</option>";
                exit();
            }
        ?>
    
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
    
        </head>
        <body>
            <div class="container">
        <form method="post" action="invoice_form.php" id="item_sel">
    
            <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
           <tr>
            <td colspan="3">
              <input type="text" name="customer" value="" placeholder="Customer Name">
            </td>
          </tr>
          <tr>
            <th>Item</th>
            <th>Service</th>
            <th>Qty</th>
    
          </tr>
    
            <tr>
              <td>
              <select name='item1' class='country'>
                    <option value="Select Item">Select Item</option>
                    <?php
    
        //                //$sql='select * from `item` order by `Sr` asc;';
        //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
        //                $stmt->execute();
        //
        //                if( $stmt->rowCount() > 0 ){
        //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
        //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
        //                    }
        //                }
    
                    ?>
    
                                <option value='ZZ2017TF11A1'>Shirt</option>
                                <option value='ZZ2017TF11A2'>Pant</option>
    
        </select></td>
    
              <td><select class="country" name="service1">
        </select></td>
        <td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
            </tr>
            <tr>
              <td>
              <select name='item2' class='country'>
                    <option>Select Item</option>
                    <?php
    
        //
        //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
        //                $stmt->execute();
        //
        //                if( $stmt->rowCount() > 0 ){
        //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
        //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
        //                    }
        //                }
    
                    ?>
    
                                <option value='ZZ2017TF11A1'>Shirt</option>
                                <option value='ZZ2017TF11A2'>Pant</option>            
        </select></td>
    
              <td><select class="country" name="service2">
        </select></td>
        <td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
            </tr>
            <tr>
                <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
                <span class="glyphicon glyphicon-save"></span> &nbsp; Save
                </button>
                </td>
            </tr>
        </table>
            <input type="button" class="add-row" value="Add Row">
        </form>
        <div id="markup_model" class="hide">
          <table>
            <tr>
              <td>
                <select name="nameitem" class="country">
                            <option>Select Item</option>
                            <?php 
        //                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC "); 
        //                        $stmt->execute();
        //
        //                        if( $stmt->rowCount() > 0 ){ 
        //                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){ 
        //                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
        //                            }
        //                        }   
                            ?>
    
                                <option value='ZZ2017TF11A1'>Shirt</option>
                                <option value='ZZ2017TF11A2'>Pant</option>                    
                        </select>
              </td>
              <td>
                <select class="country" name="namewhat"></select>
              </td>
              <td>
                <input type="text" name="nameqty" value="" placeholder="Quantity" />
              </td>
            </tr>
          </table>
        </div>
        </div>
        <script src="js/jquery-2.1.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
          var cont = 3;
          var qty = "qty";
          var item = "item";
          var what = "service";
    
          $(".add-row").click(function() {
            var nameqty = qty + cont;
            var nameitem = item + cont;
            var namewhat = what + cont;
    
            var markup = $('#markup_model tbody');
    
            $(markup).find('.country:eq(0)').attr('name', nameitem);
            $(markup).find('.country:eq(1)').attr('name', namewhat);
            $(markup).find('input').attr('name', nameqty);
    
            $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));
    
            cont++;
          });
    
    
            $('.container').on( 'change', '.country', function () {
                //console.log($(this).attr('name'));
                var oSelItem = $(this).attr('name');
                var lastChar = oSelItem.substr(oSelItem.length -1); 
                var prevChar = oSelItem.substr(0, oSelItem.length-1);
                //console.log(prevChar);
                if(prevChar === "item") {
                  var oSelService = "service" + lastChar;
                  console.log(oSelItem + "  " + oSelService); 
                  console.log($(this).val());
                  var thisId = $(this).val(); 
                 $.ajax({
                    type: 'post',
                    url: 'ajax.php',
                    data: {
                     'id':thisId,
                     'action':'get_dependent_menu'
                    },
                    success: function (response) {
                    //alert(response); 
                    console.log(oSelService);
                    $('select[name="'+ oSelService +'"]').html(response);
    
                    }
                 });         
    
                }
    
            });  
        });
        </script>
    
    
        </body>
        </html>
    
    
    
    您的问题是因为此错误-未捕获的TypeError:无法在第243行的HTMLDocument.bindEvents处将属性“onchange”设置为null。您可以在inspect元素中看到相同的情况。这是因为您正在为尚未添加的item3定义函数bindEvents。此外,这仅在添加单行的情况下有效。更改了您的逻辑并大量使用jquery。我已经注释掉了你代码中的php部分,并对其进行了硬编码。还创建了一个php文件,用于在选择框更改时发送ajax响应

        <?php // require_once '../home.php' ?>
        <?php
    
        foreach($_POST as $key => $val) {
            echo "$key => $val <br>";
        }
    
            if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
                echo "here <br>";
                ob_clean();
        //
        //        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        //        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
        //        if( $action && $id && !is_nan( $id ) ){
        //
        //            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
        //            $stmt->bindParam(':irn',$id);
        //            $stmt->execute();
        //            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
        //            $stmtin->bindParam(':irn',$id);
        //            $stmtin->execute();
        //            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );
        //
        //            if( $stmt->rowCount() > 0 ){
        //                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
        //                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
        //                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
        //                 }
        //            }
        //        }
                echo "<option value='Select Service'>Select Service (Pant)</option>";
                echo "<option value='12121211'>Iron</option>";
                exit();
            }
        ?>
    
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
    
        </head>
        <body>
            <div class="container">
        <form method="post" action="invoice_form.php" id="item_sel">
    
            <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
           <tr>
            <td colspan="3">
              <input type="text" name="customer" value="" placeholder="Customer Name">
            </td>
          </tr>
          <tr>
            <th>Item</th>
            <th>Service</th>
            <th>Qty</th>
    
          </tr>
    
            <tr>
              <td>
              <select name='item1' class='country'>
                    <option value="Select Item">Select Item</option>
                    <?php
    
        //                //$sql='select * from `item` order by `Sr` asc;';
        //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
        //                $stmt->execute();
        //
        //                if( $stmt->rowCount() > 0 ){
        //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
        //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
        //                    }
        //                }
    
                    ?>
    
                                <option value='ZZ2017TF11A1'>Shirt</option>
                                <option value='ZZ2017TF11A2'>Pant</option>
    
        </select></td>
    
              <td><select class="country" name="service1">
        </select></td>
        <td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
            </tr>
            <tr>
              <td>
              <select name='item2' class='country'>
                    <option>Select Item</option>
                    <?php
    
        //
        //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
        //                $stmt->execute();
        //
        //                if( $stmt->rowCount() > 0 ){
        //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
        //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
        //                    }
        //                }
    
                    ?>
    
                                <option value='ZZ2017TF11A1'>Shirt</option>
                                <option value='ZZ2017TF11A2'>Pant</option>            
        </select></td>
    
              <td><select class="country" name="service2">
        </select></td>
        <td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
            </tr>
            <tr>
                <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
                <span class="glyphicon glyphicon-save"></span> &nbsp; Save
                </button>
                </td>
            </tr>
        </table>
            <input type="button" class="add-row" value="Add Row">
        </form>
        <div id="markup_model" class="hide">
          <table>
            <tr>
              <td>
                <select name="nameitem" class="country">
                            <option>Select Item</option>
                            <?php 
        //                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC "); 
        //                        $stmt->execute();
        //
        //                        if( $stmt->rowCount() > 0 ){ 
        //                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){ 
        //                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
        //                            }
        //                        }   
                            ?>
    
                                <option value='ZZ2017TF11A1'>Shirt</option>
                                <option value='ZZ2017TF11A2'>Pant</option>                    
                        </select>
              </td>
              <td>
                <select class="country" name="namewhat"></select>
              </td>
              <td>
                <input type="text" name="nameqty" value="" placeholder="Quantity" />
              </td>
            </tr>
          </table>
        </div>
        </div>
        <script src="js/jquery-2.1.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
          var cont = 3;
          var qty = "qty";
          var item = "item";
          var what = "service";
    
          $(".add-row").click(function() {
            var nameqty = qty + cont;
            var nameitem = item + cont;
            var namewhat = what + cont;
    
            var markup = $('#markup_model tbody');
    
            $(markup).find('.country:eq(0)').attr('name', nameitem);
            $(markup).find('.country:eq(1)').attr('name', namewhat);
            $(markup).find('input').attr('name', nameqty);
    
            $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));
    
            cont++;
          });
    
    
            $('.container').on( 'change', '.country', function () {
                //console.log($(this).attr('name'));
                var oSelItem = $(this).attr('name');
                var lastChar = oSelItem.substr(oSelItem.length -1); 
                var prevChar = oSelItem.substr(0, oSelItem.length-1);
                //console.log(prevChar);
                if(prevChar === "item") {
                  var oSelService = "service" + lastChar;
                  console.log(oSelItem + "  " + oSelService); 
                  console.log($(this).val());
                  var thisId = $(this).val(); 
                 $.ajax({
                    type: 'post',
                    url: 'ajax.php',
                    data: {
                     'id':thisId,
                     'action':'get_dependent_menu'
                    },
                    success: function (response) {
                    //alert(response); 
                    console.log(oSelService);
                    $('select[name="'+ oSelService +'"]').html(response);
    
                    }
                 });         
    
                }
    
            });  
        });
        </script>
    
    
        </body>
        </html>
    
    
    
    在上面的代码中,您两次运行相同的查询,我认为这是复制/粘贴错误

    以下内容基于前面的问题和已经提供的帮助

    mysql> describe irn_item;
    +-------+------------------+------+-----+---------+----------------+
    | Field | Type             | Null | Key | Default | Extra          |
    +-------+------------------+------+-----+---------+----------------+
    | irn   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | name  | varchar(50)      | YES  |     | NULL    |                |
    +-------+------------------+------+-----+---------+----------------+
    
    
    mysql> select * from irn_item;
    +-----+------------+
    | irn | name       |
    +-----+------------+
    |   1 | Shirt      |
    |   2 | Trousers   |
    |   3 | Jacket     |
    |   4 | Socks      |
    |   5 | Underpants |
    |   6 | Hat        |
    +-----+------------+
    
    
    mysql> describe irn_service;
    +-------------+------------------+------+-----+---------+----------------+
    | Field       | Type             | Null | Key | Default | Extra          |
    +-------------+------------------+------+-----+---------+----------------+
    | srn         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | irn         | int(10) unsigned | NO   | MUL | 1       |                |
    | instruction | varchar(50)      | NO   |     | 1       |                |
    +-------------+------------------+------+-----+---------+----------------+
    
    
    mysql> select * from irn_service;
    +-----+-----+-----------------------+
    | srn | irn | instruction           |
    +-----+-----+-----------------------+
    |   1 |   2 | Iron                  |
    |   2 |   1 | Dry Clean Only        |
    |   3 |   3 | Hi-Pressure dry clean |
    |   4 |   4 | Steam Clean           |
    |   5 |   5 | Decontaminate         |
    |   6 |   6 | Waterproof            |
    +-----+-----+-----------------------+
    
    在不知道数据库模式的情况下,我根据原始代码中sql中的一些列创建了一个快速示例数据库。下面的代码使用的是
    mysqli
    而不是PDO,因为对于我的测试来说,它的编写速度要快得多,所以请忽略它并没有完全遵循的事实。我相信,您遇到问题的一个重要方面是,新添加的行不会复制触发ajax请求的事件处理程序。我昨天确实提到,在克隆节点时,使用
    addEventListener
    分配的任何事件处理程序都不会被复制/克隆-因此,为了确保事件处理程序被复制/克隆,您需要使用
    内联事件处理程序
    ~ie:
    ..


    在上面的代码中,您运行了两次相同的查询,我认为这是复制/粘贴错误

    以下内容基于前面的问题和已经提供的帮助

    mysql> describe irn_item;
    +-------+------------------+------+-----+---------+----------------+
    | Field | Type             | Null | Key | Default | Extra          |
    +-------+------------------+------+-----+---------+----------------+
    | irn   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | name  | varchar(50)      | YES  |     | NULL    |                |
    +-------+------------------+------+-----+---------+----------------+
    
    
    mysql> select * from irn_item;
    +-----+------------+
    | irn | name       |
    +-----+------------+
    |   1 | Shirt      |
    |   2 | Trousers   |
    |   3 | Jacket     |
    |   4 | Socks      |
    |   5 | Underpants |
    |   6 | Hat        |
    +-----+------------+
    
    
    mysql> describe irn_service;
    +-------------+------------------+------+-----+---------+----------------+
    | Field       | Type             | Null | Key | Default | Extra          |
    +-------------+------------------+------+-----+---------+----------------+
    | srn         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | irn         | int(10) unsigned | NO   | MUL | 1       |                |
    | instruction | varchar(50)      | NO   |     | 1       |                |
    +-------------+------------------+------+-----+---------+----------------+
    
    
    mysql> select * from irn_service;
    +-----+-----+-----------------------+
    | srn | irn | instruction           |
    +-----+-----+-----------------------+
    |   1 |   2 | Iron                  |
    |   2 |   1 | Dry Clean Only        |
    |   3 |   3 | Hi-Pressure dry clean |
    |   4 |   4 | Steam Clean           |
    |   5 |   5 | Decontaminate         |
    |   6 |   6 | Waterproof            |
    +-----+-----+-----------------------+
    
    在不知道数据库模式的情况下,我根据原始代码中sql中的一些列创建了一个快速示例数据库。下面的代码使用的是
    mysqli
    而不是PDO,因为对于我的测试来说,它的编写速度要快得多,所以请忽略它并没有完全遵循的事实。我相信,您遇到问题的一个重要方面是,新添加的行不会复制触发ajax请求的事件处理程序。我昨天确实提到,在克隆节点时,使用
    addEventListener
    分配的任何事件处理程序都不会被复制/克隆-因此,为了确保事件处理程序被复制/克隆,您需要使用
    内联事件处理程序
    ~ie:
    ..


    您确实需要更改这里的逻辑,很抱歉,在这种情况下静态处理动态内容将不起作用。。。如果我们有4号线、5号线和10号线怎么办。。您确实需要为所有元素集提供一个公共类,然后使用event delegation
    on()
    附加事件,这样动态添加的新元素也将绑定

    例如,将项目列中的
    country
    类更改为
    item
    ,将服务列中的
    country
    类更改为
    service

    $('body').on('change', '.item', function(){
       //You're ajax logic here
       //Try to use `$.post()` instead 
       //Target the related service list like
       var related_service_select = $(this).closest('tr').find('.service');
       //Now you can fill it with the server side response
    });
    

    希望这能有所帮助。

    您确实需要更改这里的逻辑,很抱歉,静态处理动态内容在这种情况下不起作用。。。如果我们有4号线、5号线和10号线怎么办。。您确实需要为所有元素集提供一个公共类,然后使用event delegation
    on()
    附加事件,这样动态添加的新元素也将绑定

    例如,将项目列中的
    country
    类更改为
    item
    ,将服务列中的
    country
    类更改为
    service

    $('body').on('change', '.item', function(){
       //You're ajax logic here
       //Try to use `$.post()` instead 
       //Target the related service list like
       var related_service_select = $(this).closest('tr').find('.service');
       //Now you can fill it with the server side response
    });
    

    希望这有帮助。

    您能用您的代码编辑我的代码吗。问题中的代码是该页面的完整代码,因此我请求您添加/编辑我的代码和您的代码。另外,在你添加代码的地方添加注释。你能用你的代码编辑我的代码吗。问题中的代码是该页面的完整代码,因此我请求您添加/编辑我的代码和您的代码。另外,在添加代码的地方添加注释。服务选择没有提供任何选项,就像前两个一样,但在演示中我发现前两个也是空的。@ZakariaAcharki服务选择仅在项目选择具有选定选项时才会提供选项!是的,正在检查..您确实需要更改这里的逻辑,很抱歉,静态处理动态内容在这种情况下不起作用…服务选择没有提供任何选项,正如前两个提供的那样,但在演示中,我发现前两个也为空..@ZakariaAcharki服务选择仅在项目选择具有选定选项时才提供选项!是的,正在检查..您确实需要更改这里的逻辑,很抱歉,静态处理动态内容在这种情况下不起作用…它帮助了我,感谢您宝贵的时间。但它并没有添加新行。我认为您现在出现错误的原因是(顺便检查控制台-关于引导和jquery以及
    uncaughttypeerror有一个错误:无法读取null的属性'nextSibling'