在td点击更改按钮值

时间:2014-02-14 07:23:26

标签: javascript php jquery html

我目前有一张空白<td>的表格。每次单击<td>时,它都会更改其背景颜色。 我想更改rcStatus按钮的值以及颜色。 这是我目前的代码:

HTML:

foreach( //conditionals ){ 
    <td id="changeStatus">
       <input type="button" name="rcStatus" id="rcStatus" value=""/>
    </td>
}

的javascript:

 $('#table #td').click(
   function(){
       var cell = $(this),
       state = cell.data('state') || 'first';

   switch(state){
       case 'first':
       cell.addClass('red');
       cell.data('state', 'second');  
       document.getElementById('rcStatus').value = "missed";
       break;
     // other cases here 
   }
 });

问题是,由于我的<td>在foreach语句中,因此输入名称不是唯一的。 因此,更改onclick的唯一按钮值是表格中的第一个按钮。

无论如何,我可以修复此问题,以便更改的按钮是<td>点击内的按钮? 谢谢!

4 个答案:

答案 0 :(得分:3)

id更改为class

foreach( //conditionals ){ 
    <td class="changeStatus">
       <input type="button" name="rcStatus" id="rcStatus" value=""/>
    </td>
}

$('#table .changeStatus').click(
var that=this;
   function(){
       var cell = $(this),
       state = cell.data('state') || 'first';

   switch(state){
       case 'first':
       cell.addClass('red');
       cell.data('state', 'second');

**update:**

$(that).find('input[type="button"]').val("missed"); 
       //document.getElementById('rcStatus').value = "missed";
       break;
     // other cases here 
   }
 });

更新:假设表格的ID为#table

答案 1 :(得分:3)

这应该可以完成这项工作,但是不止一次使用ID是不好的方式。

<script>
    $('#table td').click(
      function(){
          var cell = $(this);
          state = cell.data('state') || 'first';

      switch(state){
          case 'first':
          cell.addClass('red');
          cell.data('state', 'second');
          this.getElementsByTagName('input')[0].value = "missed";
          break;
        // other cases here 
      }
    });
</script>

这里是纯Javascript的解决方案:

var table = document.getElementById("table");
var tds = table.getElementsByTagName("td");
for(var i = 0; i < tds.length;i++ ){
    tds[i].addEventListener("click", function(){
        var that = this;
        that.getElementsByTagName("input")[0].value = "missed";
    }, false);
}

答案 2 :(得分:0)

如果您想更改所有td点击的按钮文字,那么

更改

$('#table #td').click

$('#table td').click

此外,使用班级

<td class="changeStatus">

$('.changeStatus').click

答案 3 :(得分:0)

如果我了解您,您遇到的问题是选择“向右”按钮来更改点击处理程序中的值。如果您可以将$key$value条件中的foreachtd附加到inputtd的ID,则应该能够通过从input的ID中检索该子字符串并将其附加到input来准确选择它。

或者,您可以从td的子节点找到foreach($statuses as $key=>value) { ?> <td id="changeStatus_<?php echo $key; ?>"> <input type="button" name="rcStatus_$key" id="rcStatus_<?php echo $key; ?>" value=""/> </td> <?php } ,无论哪种方式,您都必须修改处理函数以将事件作为参数接收。

php中的

$('#table td').click(function(event) {
  var cell = $(this),
      id = cell.id.split('_')[1],
      state = cell.data('state') || 'first';

  switch(state) {
  case 'first':
    cell.addClass('red');
    cell.data('state','second');
    cell.children('#rcStatus_'+id).val('missed');
    break;
  // case '*':
  }
}

在js中

{{1}}
相关问题