如何在通过append
或AJAX加载的内容上运行jQuery?我已经尝试了.live
和.on
,但我所做的一切似乎都没有用,我找到的大多数内容都是针对已删除的.live
。
我正在尝试进行实时搜索,但我将其用于输入,您可以在页面上添加任意数量的输入。
$(document).ready(function() {
// ================================ live material search ============================ //
var obj;
//$('input[rel="m-live"]').focus(function(){
$('input[rel="m-live"]').on('focus',function(){
if($(this).attr('name') == obj){} else { $('#live-search-result').html(""); }
obj = $(this).attr('name');
//if($(this).val !== null){ str = "t=s&v=" + $(this).val(); ajax(str); }
var offset = $(this).offset(),
height = $(this).height() + 10;
offset.top = offset.top + height;
$('#live-search-result').show();
$('#live-search-result').css({"left":offset.left ,"top":offset.top})
});
$('input[rel="m-live"]').focusout(function(){
$('#live-search-result').hide();
});
$('input[rel="m-live"]').keyup(function(){
var str = "t=s&v=" + $(this).val();
ajax(str);
});
function ajax (str) {
$.ajax({
url: '/esystem/pages/ajax/material.php',
type: 'post',
dataType: 'text',
data: str,
success: function(data)
{
$('#live-search-result').html(data);
}
});
}
});
附加代码:
function Add(){
$('#material-list').append("<div class='material'><div class='input'>" +
"<input type='text' rel='m-live' name='mat-"+curMat+"' placeholder='Material' />" +
"<div class='logo'><i class='icon-inbox'></i></div></div> <div class='input'>" +
"<input type='text' rel='m-price' name='mat-p-"+curMat+"' placeholder='price 0.00' />" +
"<div class='logo'><i class='smaller icon-gbp'></i></div></div></div>"
);
}
function Remove(){
$('#material-list .material:last-child').remove();
}
我在那里有.on
但是对附加的输入不起作用。
旁注:空白输入的默认值是多少?正如你在代码中看到的那样,如果输入在焦点上不是空白的话,我试图再次运行AJAX,但它会运行任何东西。
然后我希望能够在带有ajaxed内容的实时搜索框中运行jQuery,以便在点击时自动填写名称和价格。
<?php
include '../../core/php/config.php';
$n = $_POST['v'];
$t = $_POST['t'];
if(!empty($n) && $t == "s"){
//$sql = "SELECT * FROM _materials WHERE name LIKE '$n'";
$sql = "SELECT * FROM _materials";
foreach ($dbh->query($sql) as $row){
if (strpos($row['name'], $n) !== FALSE){
echo $row['name'] .' - £'. $row['price'] . '<br />';
}
else{
//echo "not found";
}
}
}
?>
答案 0 :(得分:1)
要在已添加到DOM的元素上触发事件,您需要在将元素添加到DOM之后设置绑定,或者使用如下所示的.on
$(document).on('click','#SomeButtonID',function(e) {
alert("i have been clicked");
});
$("body").append('<button id="SomeButtonID">Click Me</button>');