如何获得由PHP while循环创建的点击值

时间:2018-07-30 06:01:55

标签: javascript php jquery

我正在从数据库中检索2列并将其显示在表中。现在我想在第一列上给出onCLick(),这是DesignNo。现在的问题是每个td都没有唯一的ID,那么如何获取td标签的值并调用下一个脚本?

显示表格

<table>
     <tr>
         <th>Design No.</th>
         <th>Design</th>
     </tr>
    <?php while($row = mysqli_fetch_array($res)) { ?>
        <tr>
            <td id="designno" onClick="SingleImage();"><?php echo $row['DesignNo']; ?></td>
            <td><img class="productimg" src="php/<?php echo $row['DesignImage']; ?>"></td>
        </tr>
    <?php } ?>
</table>

SingleImage()

        var date = document.getElementById("txtdate").value;
        var designno = document.getElementById("designno").innerText;
        var http = new XMLHttpRequest();
        var url = 'php/LineUpProductDisplaySingle.php';
        var params = 'date='+date+'&designno='+designno;
        http.open('POST', url, true);

        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        http.onreadystatechange = function() {//Call a function when the state changes.
           if(http.readyState == 4 && http.status == 200) {
              document.getElementById("main").innerHTML = this.responseText;
           }
        }
        http.send(params);
     }

3 个答案:

答案 0 :(得分:0)

只需将this传递给函数即可。

function SingleImage(elm){
  alert(elm.innerText);
}
<table>
  <tr>
    <th>Design No.</th>
    <th>Design</th>
   </tr>
   <tr>
     <td onClick="SingleImage(this);">A</td>
     <td>img</td>
   </tr>
   <tr>
     <td onClick="SingleImage(this);">B</td>
     <td>img</td>
   </tr>
</table>

答案 1 :(得分:0)

要在没有在HTML中定义内联事件处理程序的情况下执行此操作,可以使用document.querySelectorAll定位DOM中的特定节点,然后遍历该集合并分配事件处理程序。通过将ajax代码删除到一个单独的函数中,您可以重复使用它以满足其他需求,而不必每次都编写相同的代码。

document.addEventListener('DOMContentLoaded',function(){

    var _ajax=function( url, params, callback ){
        var http = new XMLHttpRequest();
        http.onreadystatechange = function() {
            if( this.readyState==4 && this.status==200 ) callback.call( this, this.response )
        };
        http.open( 'POST', url, true );
        http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http.send( params );
    }

    var col=Array.prototype.slice.call( document.querySelectorAll('table tr td[2]') );
        col.forEach( function( node ){
            node.addEventListener('click',function(e){
                _ajax.call( this, 'php/LineUpProductDisplaySingle.php', 'date='+document.getElementById("txtdate").value+'&designno='+this.innerText, function(r){ document.getElementById("main").innerHTML = r; } );
            }.bind( node ),false);
        });
},false);

答案 2 :(得分:0)

首先不要使用重复的id代替class并分配class

  

name ='designno'

在“ designno”点击事件中输入以下代码

尝试使用jQuery

var design_no = $(this).closest('tr').find('.designno');