我们正在创建一个管理控制台,客户将自行更新他的网站。
为此,我们使用 js 和 PHP (ajax) 创建 div :
$(document).ready(function($)
{
function loadContent(page)
{
$.ajax(
{
url: 'contenu/contenu.php',
type: 'POST',
dataType: 'html',
data:
{
'onglet': page
},
success:function(contenu)
{
console.log("success");
$("div."+page).html(contenu);
}
})
};
});
以及 PHP 代码(只是其中的一部分):
$reponse = $db->query('SELECT * FROM philosophie');
$data = $reponse->fetch();
//maj de la version FR de philosophie
echo '<form action="#" method="POST">
<label>Texte en français :</label><br/>
<textarea name="texte_fr">'.$data["texte_fr"].'</textarea><br/>
<br />
<input type="button" id="maj_philosophie_fr" value="Mettre à jour ce texte" />
<br /><br />';
该表单出现在网站上,效果很好。
之后,我想知道有多少个 id 以“maj_”开头的按钮位于具有以下代码的网站内:
alert($("[id^='maj_']").length);
我还有 0 个回复。
该元素尚未准备好,我无法在我的 div 上获取更改事件。
我看到 firebug 中的元素(DOM 部分),它们是红色字符。
请问你有什么想法吗?
最佳答案
看起来您的警报在调用成功函数之前就已运行。尝试将警报移至其中,更好的是,使用 setTimeout 将其放入下一个事件周期中。
$(document).ready(function () {
function loadContent (page) {
$.ajax({
url: 'contenu/contenu.php',
type: 'POST',
dataType: 'html',
data: { 'onglet': page },
success: function (contenu) {
console.log("success")
$("div."+page).html(contenu)
setTimeout(function () {
alert($("[id^='maj_']").length)
}, 100)
// might even work with 0, if the dom render function
// is the very next thing in the queue
}
})
}
})
如果您必须处理许多嵌套的 ajax 调用,您可能需要考虑使用 Promise api。 Here are the docs for the jQuery implementation of $.promise()
确保代码在调用成功函数后运行并不是可以解决的问题。代码在接收数据之前无法知道数据,这意味着要么嵌套成功回调,要么使用其他解决方案,例如链接命名函数回调,或者最好是 Promise。
关于php - 加载我的页面后元素不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30148868/