MVC - 在 ajax 调用中操作 Jquery 插件属性

MVC - Manipulate Jquery plug in properties in ajax call

本文关键字:操作 Jquery 插件 属性 调用 ajax MVC      更新时间:2023-09-26

我正在使用来自 http://labs.perifer.se/timedatepicker/的Jquery时间选择器

在视图中,我有这个时间选择器控件。

   $("#startTime").timePicker({
        startTime: "09.00", 
        endTime: new Date(0, 0, 0, 19, 0, 0), 
        show24Hours: false,
        separator: '.',
        step: 30
    });

如果先前选择了特定时间(例如上午 11:00)(并保存在 db 中),则应禁用该特定选项,并且不可用于后续选择。在MVC控制器中,通过服务层,我得到了所有先前选择的时间的"列表"。

    public ActionResult DisableTimes(param1, param2)
    {            
        List<string> listTimes = Webservice(param1,param2);
        //getting previously saved times - above line
        return Json(listTimes, JsonRequestBehavior.AllowGet);
    }

我正在像这样的java脚本函数中进行ajax调用,该函数将参数传递给MVC控制器并返回时间列表。

       $.ajax({
          "url": "/ControllerName/DisableTimes/",
          "type": "get",
          "dataType": "json",
          "data": { param1: $("#paramval1").val(), param2: $("#paramvalue2").val() },
          "success": function (listTimes) {
              //Code here - use the listTimes values and disable the 
              //appropriate timepicker drop down choices.
               }
           });

如何利用我从控制器获得的时间列表"listTimes"来禁用 Jquery 时间选择器选项?

您应该能够通过以下方式从可用选项中删除 li:

$(listTimes).each(function() {
    $('.time-picker').find('li:contains("' + this + '")').remove();
});

编辑:

但是,如果页面上有多个时间选择器,那会有点困难。您应该能够添加:first选择器以仅获取第一个时间选取器。

$('.time-picker:first').find('li:contains("' + this + '")').remove();

现场演示

显然这个日期选择器插件没有给你删除他的行为的可能性。

但我确实相信您可以从文档中删除该元素。

,然后再次重新添加。

用:

http://api.jquery.com/remove/

http://api.jquery.com/add/

或者你可以每次有两个元素,显示/隐藏你需要的东西或使用:

http://api.jquery.com/hide/

http://api.jquery.com/show/

默认情况下

,插件似乎不提供该功能。我会稍微更改插件代码中的这些行(它附加到列表中的位)

// Build the list
    for(var i = 0; i < times.length; i++) {
      $tpList.append("<li>" + times[i] + "</li>");
    }

到为每个 li 添加一些标识符的东西:

for(var i = 0; i < times.length; i++) {
      $tpList.append("<li class='"+times[i]+'">" + times[i] + "</li>");
    }`

只是为了更容易地选择这些 li 元素,然后在您的成功处理程序中执行以下操作:

    "success": function (listTimes) {
         $(listTimes).each(function(i,item){
               $('li.'+item).remove();
         });
        //or may be if you are just getting an array of strings from the webservice then something like this will be enough: $('.'+listTimes.join(',.')).remove();
     }

并将时间选择器插件调用 $("#startTime").timePicker 放在 ajax 成功回调中,这样就没有竞争条件,因为 ajax 回调可能会在插件初始化后发生。

另一种选择是处理 $('#startTime').change 并检查是否不允许时间并向用户显示错误。