在jquery mobile中提交表单后重新显示页面会丢失我附加的事件

时间:2012-06-06 17:40:03

标签: jquery-mobile

我有一个多页文档,但我一直在显示html并在一个php文件中对单个页面进行验证:

<div id="checkPage" data-role="page">
  <div data-role="header">
    <h1>Page Title</h1>
  </div>
  <div data-role="content">
    <?php
    $form = $_REQUEST['form'];  //this is simply a hidden input in my form that I reference to know if a form submission has occurred
    if($form) {
      $res = process();
      if(is_array($res)) { //if the data is an array then it is an array of errors that I will display to the user
        $html = page($res); 
      } else {
        $html = $res;  //if the data is not an array then it is confirmation html that the request was successful.
      }
    } else {
      $html = page();
    }
    echo $html;
    ?>
  </div>
</div>

在我的page()函数中,我在HTML之后附加了一些jquery:

$detail .= chr(10) . '<script type="text/javascript">';
$detail .= chr(10) . '$( "#checkPage" ).bind( "pageinit",function(event){';
$detail .= chr(10) . '  $("#txtAmount").change(function(){';
$detail .= chr(10) . '    alert("INSIDE");';
$detail .= chr(10) . '  });';
$detail .= chr(10) . '});';
$detail .= chr(10) . '</script>';
return $detail;

当我导航到我的页面然后输入(并保留)金额文本框时,我会看到警报。如果单击页面上的取消按钮(我将其重定向到另一个页面),我也会看到警报,然后再次通过菜单超链接返回并再次键入(并保留)文本框。但是,如果我提交表单,发现验证错误并重新显示页面,则不会再次设置pageinit。即使我不使用pageinit逻辑,也不再设置更改事件。

我做错了什么?我感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

修改DOM时,实际上会获得一组全新的元素。绑定到被替换元素的事件已经消失,因为原始DOM元素不再存在。请参阅jQuery FAQ

http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F

您可以使用jQuery.live绑定到现在和将来匹配的元素。

http://api.jquery.com/live/

或者,您可以将绑定逻辑放在一个公共函数中,并在Ajax成功后调用它,如此处所述

http://jetlogs.org/2009/01/29/re-binding-jquery-events-on-ajax-callbacks/

答案 1 :(得分:0)

这是最终奏效的。 Eric J.确实让我走上正轨。

$detail .= chr(10) . '<script type="text/javascript">';
$detail .= chr(10) . '$("#txtAmount").die("change");';
$detail .= chr(10) . '$( "#txtAmount" ).live( "change",function(event){';
$detail .= chr(10) . '  alert("CHANGE");';
$detail .= chr(10) . '});';
$detail .= chr(10) . '</script>';

如果没有死亡,那么如果我离开并返回它将被多次调用。但是如果没有现场表单,那么在表单提交后它将无效。

相关问题