我知道如果你使用ajax在带有表单元素的页面中加载div,那么你必须使用live函数将事件添加到那些不在dom树中的元素....
我还在jQuery网站上看到,实时功能目前不支持焦点,模糊等....
当通过ajax加载到div中的元素被聚焦或模糊时,我应该怎么做才能调用函数??
应该用bind来完成吗?但是谈到bind,即使live和bind看起来有点相似,也不能在上面提到的场景中使用......对...?
这里是代码......
<BODY style="">
<div style="margin-top:5px; width:100%" class="subAndContent" id="subAndContent">
<!-- TABLE TO HOLD SUB MENU-->
<div id="subMenuDiv">
<table width="100%" >
<tr align="center" valign="middle">
<td width="100%" valign="middle" class="rounded" >
<div class="sidebarmenu">
<ul id="sidebarmenu1">
<li>
<a href="javascript:ajaxLoadMainOnly('createHotel.php', 'content')" > <!-- This function get's the page to be loaded and the div into which it should be loaded and uses ajax to do the loading... -->
HOTEL
</a>
</li>
<li>
<a href="javascript:ajaxLoadMainOnly('createCountry.php', 'content')" >
COUNTRY
</a>
</li>
<li>
<a href="javascript:ajaxLoadMainOnly('createCity.php', 'content')">
CITY
</a>
</li>
</ul>
</div>
</td>
</tr>
</table> <!-- END TABLE TO HOLD SUB MENU-->
</div>
<div id="contentDiv" class="rounded">
<!-- TABLE TO HOLD CONTENT PANE-->
<table width="100%" style="float:left;">
<tr valign="left">
<td align="center">
<div id ="content">
<!-- Div into which the content will be loaded -->
</div>
</td>
</tr>
</table>
</div>
</div>
<!-- DIV AND TABLE TO HOLD FOOTER -->
<?php
include 'footer.php';
?>
</BODY>
答案 0 :(得分:1)
您必须掌握动态加载的元素,然后使用bind添加焦点和模糊处理程序。例如,如果要将处理程序添加到带有“longtext”类的textarea,则可以使用以下内容:
$.getJSON('createHotel.php', { /* params go here */ }, receiveHotelCreated);
function receiveHotelCreated(data) {
$('#content textarea.longtext').bind('blur', onTABlur);
}
function onTABlur() {
var ta = $(this); // The textarea on which the blur event occurred
alert('Textarea blurred');
// Your code goes here
}
当焦点离开textarea时,将调用onTABlur(TA =文本区域)函数。在函数内部,this
指的是调用函数的元素。当我们收到AJAX响应(receiveHotelCreated
)时将它绑定到文本区域,这将是所需的文本区域元素。我们将this
包装在jQuery函数($(this)
)中以获得一些额外的功能。
答案 1 :(得分:0)
我相信我读到下一版本的jQuery(1.4)涵盖了Live的剩余事件。
但是现在,使用1.3,你需要使用bind(或“click”之类的快捷方式)。是的,如果你向页面添加元素而Live不能用于你正在做的事情,你需要绑定添加的内容。
documentation for "Live"是一个很好的起点。我想如果你想处理Live还没有处理的事件,你仍然可以使用liveQuery插件。
答案 2 :(得分:0)
这是一个简单的例子:
每次调用ajax请求时,都会取消绑定并重新绑定焦点事件。取消绑定只是为了安全,并确保没有任何剩余事件。
$(document).ready(function() {
focusEventFunction();
ajaxLoader();
}
function ajaxLoader();
$('#sidebarmenu1 a').unbind().bind('click', function(event){
$.get('url_to_get.php', function(data) {
// CODE THAT REPLACES DIVS AND DATA
//The following has to be inside the ajax callback and
//after the code that changes divs. this will remap all the functions
//that bind the focus.
$('selector_for_elements_needing_focus').unbind().bind('focus', function(event){
focusEventFunction($(this), event)
ajaxLoader(); //this ensures your ajax gets called again,
//depending on the complexity of the html changes
//you may not need this.
}
}
function focusEventFunction(jElement, event) {
//just a dummy function that does your focus/blur stuff.
// you might not need the parameters
}