2012-03-01 21 views
0

我使用PHP/Java腳本提交 - 從鏈接http://alexmarandon.com/articles/web_widget_jquery/ 而在我的項目alexmarandon的Widget是:如何運行的jQuery時單擊用PHP的JavaScript控件

script.js 
html.php 
demo.html 

在腳本中,我使用代碼:

(function() { 

// Localize jQuery variable 
var jQuery; 

/******** Load jQuery if not present *********/ 
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.7.1') { 
    var script_tag = document.createElement('script'); 
    script_tag.setAttribute("type","text/javascript"); 
    script_tag.setAttribute("src", 
     "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"); 
    if (script_tag.readyState) { 
     script_tag.onreadystatechange = function() { // For old versions of IE 
      if (this.readyState == 'complete' || this.readyState == 'loaded') { 
       scriptLoadHandler(); 
      } 
     }; 
    } else { 
     script_tag.onload = scriptLoadHandler; 
    } 
    // Try to find the head, otherwise default to the documentElement 
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); 
} else { 
    // The jQuery version on the window is the one we want to use 
    jQuery = window.jQuery; 
    main(); 
} 

/******** Called once jQuery has loaded ******/ 
function scriptLoadHandler() { 
    // Restore $ and window.jQuery to their previous values and store the 
    // new jQuery in our local jQuery variable 
    jQuery = window.jQuery.noConflict(true); 
    // Call our main function 
    main(); 
} 

/******** Our main function ********/ 
function main() { 
    jQuery(document).ready(function($) { 
     /******* Load CSS *******/ 
     var css_link = $("<link>", { 
      rel: "stylesheet", 
      type: "text/css", 
      href: "style.css" 
     }); 
     css_link.appendTo('head');   

     /******* Load HTML *******/ 
     var jsonp_url = "data.php?callback=?"; 
     $.getJSON(jsonp_url, function(data) { 
      $('#example-widget-container').html(data); 
     }); 
     $('.submit').click(function(){ 
      alert('test'); 
     }); 
    }); 
} 

})(); // We call our anonymous function immediately 

然後我data.php

$str = '<div class="widget_advance">'; 
$str .= '<form method="post" id="form_widget_advance">'; 
$str .= '<input type="submit" value="Tìm" class="submit" />'; 
$str .= '</form>'; 
$str .= '</div>'; 

echo $_GET['callback'] . '(' . json_encode($str) . ');'; 

調用數據最後,在demo.html結果是:

<script src="script.js" type="text/javascript"></script> 
<div id="example-widget-container"></div> 

=>當我點擊按鈕提交的結果沒有顯示alert('test');如何適應它?

回答

1

將這個裏面這樣:

$.getJSON(jsonp_url, function(data) { 
    $('#example-widget-container').html(data); 
    $('.submit').click(function(){ 
    alert('test'); 
    }); 
}); 

你看,它必須是在回調中。如果它不在DOM中,則不能綁定到提交按鈕。你也可以做一些事情:$("#someForm").submit(function() { ... });

相關問題