2014-10-28 82 views
0

我有添加一些动态操作的窗体。我有一张表,其中我有申请人申请的 职位。有一个offer offer按钮,当他们点击offer按钮时,我想插入要提交和更新的offer字段。我可以得到要插入的域,但是当我点击取消事务按钮时,我无法让它清空构建窗体的div addapptrans。以下是代码。我知道这一定是我失踪的简单事情。jquery不会删除div

<head> 
<script type="text/javascript"> 

    $(function(){ 
     $(".offerposition").click(function(){ 
      var row = $(this).closest('tr').find('td:nth-child(1)').text(); 

      alert('You clicked on ' +row); 
      $("#addapptrans").empty(); 
      $("#addapptrans").append(
       $("<input>").attr('type','hidden').attr('value',row).attr('Name','Mchposid')) 
      .append(
       $("<input>").attr('type','submit').attr('value','Complete Offer').attr('id','completeoffertrx').attr('name','completeoffertrx').addClass("buttonlarge buttonmargin") 
      ).append(
       $("<input>").attr('type','button').attr('value','Cancel Transaction').attr('id','canceloffertrx').attr('name','canceloffertrx').addClass("buttonlarge buttonmargin") 
      ); 

     } 
     ) 
    } 
    ); 

    $(function(){ 
     $("#canceloffertrx").click(function(){ 
     $("#addapptrans").empty(); 

     }) 
    }) 
</script> 
</head> 
<body> 

<form > 

    <div id="addapptrans"></div> 
    <p class="posttitle">Positions applied For</p> 
    <table class="tabpositions"> 

     <tbody> 
     <tr> 
      <th class="position">Position</th> 
      <th class="department">Department</th> 
      <th class="dateapp">Date Applied</th> 
      <th class="appdate">Offer?</th> 
     </tr> 

     <tr> 
      <td style="display: none;">2281</td> 
      <td>Building Service Worker - Part time</td> 
      <td>Environmental Services</td> 
      <td>08/13/2001</td> 
      <td><input type="button" class="offerposition" value="Offer Position"></td> 
     </tr>     
     </tbody> 
    </table> 

</form> 

+0

你能提供一个小提琴吗? – GSaunders 2014-10-28 17:40:16

回答

2

这这里代码:#canceloffertrx

$(function(){ 
    $("#canceloffertrx").click(function(){ 
     $("#addapptrans").empty(); 
    }) 
}) 

奔跑存在在页面上。因此,$("#canceloffertrx").click(fn)在页面上匹配零个元素,并将点击处理程序绑定到它们的全部零。


您可以通过将点击处理程序绑定到文档或存在的最接近的父级来解决此问题。

$('#addapptrans').on('click', '#canceloffertrx', function(){ 

这就是说,当元素#addapptrans接收匹配选择#canceloffertrx是实际点击一个一个点击事件,和元素,触发事件处理函数。

或者通过在创建按钮时绑定点击处理程序。

$("<input>") 
    .attr('type','submit') 
    .attr('value','Complete Offer') 
    .attr('id','completeoffertrx') 
    .attr('name','completeoffertrx') 
    .addClass("buttonlarge buttonmargin") 
    .click(function() { ... }); 

最后,一些样式建议:)特别是链接jQuery方法时,你可以把这使得它更具可读性它自己的行中的每个电话。

而且您还应该知道attr()可以接受一个对象作为参数,只需调用一次即可设置许多属性。

$("<input>") 
    .attr({ 
    type: 'submit', 
    value: 'Complete Offer', 
    id: 'completeoffertrx', 
    name: 'completeoffertrx' 
    }) 
    .addClass("buttonlarge buttonmargin") 
    .click(function() { ... }); 
+1

最好将委派的事件处理程序附加到最近的不变祖先元素(例如,在这个问题中'#addapptrans')。如果没有更近的话,“文件”就是后备。 – 2014-10-28 17:43:06

+0

您的解决方案http://jsfiddle.net/jn7jh3bm/ – jbyrne2007 2014-10-28 17:44:12

+0

注意并更正! :) – 2014-10-28 17:44:16