我有一个MVC应用程序,它想要在Controller视图之一上隐藏和显示div。
所以我有一个父视图,
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
和一个js代码,
$(document).ready(function () {
$.ajax({
type: 'GET',
url : '@Url.Action(actionName: "Action1", controllerName: "Controller1")',
dataType: "html",
async:true,
success: function (result) { $("#div1").html(result); }
});
$.ajax({
type: 'GET',
url : '@Url.Action(actionName: "Action2", controllerName: "Controller2")',
dataType: "html",
async:true,
success: function (result) { $("#div2").html(result); }
});
$.ajax({
type: 'GET',
url : '@Url.Action(actionName: "Action3", controllerName: "Controller3")',
dataType: "html",
async:true,
success: function (result) { $("#div3").html(result); }
});
});
这将使用控制器视图加载div。但是我想一次显示一个div。每个div停留10秒。 还有一种更好的方法来编写$(document).ready(function()吗? 预先感谢
答案 0 :(得分:0)
$(function() {
var divs = $(".myDiv");
var sampleImageList = ["animals", "arch", "nature"];
// make your ajax calls and insert it into respective div
var request = function(action, controller, div) {
var url = "@Url.Action(actionName: " + action + "," + "controllerName: " + controller + ")";
var index = $(divs).index(div);
var sampleImage = "<img src=\"https://placeimg.com/640/480/" + sampleImageList[index] + "\">";
$(div).html(sampleImage);
/* use ur Ajax call
$.ajax({
type: 'GET',
url: url,
dataType: "html",
success: function(result) {
$(div).html(result);
},
error: function(xhr, status) {
$(div).html(status); // handle error here
}
}); */
};
var swap = function() {
var $active = $("#myGallery .active");
var $next = ($("#myGallery .active").next().length > 0) ? $("#myGallery .active").next() : $("#myGallery div:first");
$active.fadeOut(function() {
$active.removeClass("active");
$next.fadeIn().addClass("active");
});
}; // swap end
divs.each(function(index, div) {
var action = $(div).attr("data-action");
var controller = $(div).attr("data-controller");
request(action, controller, div);
}); // divs end
$("#myGallery .active").fadeIn(); // show first div
setInterval(swap, 10000);
});
#myGallery .myDiv{
display : none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="myGallery">
<div id="div1" class="myDiv active" data-action="first" data-controller="home"> </div>
<div id="div2" class="myDiv" data-action="second" data-controller="home"></div>
<div id="div3" class="myDiv" data-action="third" data-controller="home"></div>
</div>