jQuery不处理Ajax动态添加内容



添加内容后,我正在使用ajax动态添加内容,我正在尝试使用jquery更改背景图像,它不起作用这是我的代码。

阿贾克斯代码:

function loadlogin(url, loginFunction)
{
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200) 
{
loginFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}

这是我的jquery代码:

<div class="img-fluid" src="img.png">
<script>
$(document).on( "click", ".img-fluid", function(event) {
var background = $(this).attr("src");
$(".fullpage_wrapper").css("background","url(" + background + ")");
});
</script>

请帮我解决这个问题。

你可以使用ajaxCompletefunc,所以每当Ajax请求完成时,jQuery都会触发ajaxComplete事件。

例如:

<div class="log"></div>
<script>
$(document).ajaxComplete(function() {
$(".log" ).text( "Triggered ajaxComplete handler." );
//your code here
});
</script>

没有 ajaxcomplete(使用background-image代替background(:

$(document).ready(function() {
var background=$(".img-fluid").attr("data-src");
$(".fullpage_wrapper").css("background-image","url("+background+")");

});
.fullpage_wrapper
{
width:300px;
display:block;
height:60px;
background-color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test" class="fullpage_wrapper"></div>
<div class="img-fluid" data-src="https://api.jquery.com/jquery-wp-content/themes/jquery/images/logo-jquery.png">

更新 :您可以使用.css()而不是:

document.getElementById("test").style.backgroundImage = "url('background')"; 

然后将 ID(我用test(名称添加到您的类中。

最新更新