首页 \ 问答 \ jQuery .on()方法在Firefox上而不是在Chrome上(jQuery .on() method woking on Firefox but not on Chrome)

jQuery .on()方法在Firefox上而不是在Chrome上(jQuery .on() method woking on Firefox but not on Chrome)

我正在尝试在我的网页上创建一个特定的功能,它使用jQuery迭代JSON对象,使用其值填充组合框,并使用jQuery的.on()方法将click事件处理程序附加到选项。

在我决定在Google Chrome上测试功能之前 ,一切似乎都运行正常 (到目前为止,我一直在开发Firefox Developer Edition)。 来自jQuery的.on()方法似乎根本不适用于谷歌浏览器。

这是我的网页的HTML代码段

<div id="showotherinfo">
    <div class="form-group" id="existingRedirection" style="">
        <label for="serviceNameList">Select a Pretty Redirection to edit it, or add a new one below</label>
        <select class="form-control" id="serviceNameList" name="serviceNameList">
            <option value="0">-Add New-</option>
            <option value="57">Infibeam Redirection</option>
            <option value="53">Mozilla Developers Redirection</option>
            <option value="56">SnapDeal Redirection</option>
        </select>
        <hr style="height: 1px; border: none; color: #333; background-color: #333;">                                                    
    </div>
    <div class="form-group">
        <label for="name">Service Name<font color="red" size=3>*</font></label> 
        <input class="form-control" name="name" id="name">  
    </div>
     <div class="form-group">
        <label for="serviceUrl">Target URL<font color="red" size=3>*</font></label> 
        <input class="form-control" name="serviceUrl" id="serviceUrl">
    </div>
    <label for="prettyUrl">Pretty URL<font color="red" size=3>*</font></label>
    <div class="form-inline">
        <div class="form-group">
            <input type="text" class="form-control" name="prettyUrl" id="prettyUrl" >
        </div>
    </div>
    <div class="form-group" style="margin-top: 19px;">
        <label for="redirectType">Redirect Type<font color="red" size=3>*</font></label> 
        <select class="form-control"
            name="redirectType" id="redirectType">
            <option value="0" SELECTED>-Redirection Type-</option>
            <option value="307">Temporary(307)</option>
            <option value="301">Permanent(301)</option>
            <option value="302">Found(302)</option>
        </select> 
    </div>
    <div class="checkbox">
        <label style="font-weight: bold;">
            <input type="checkbox" name="nofollow" id="nofollow">
            NoFollow this link
        </label> 
    </div>
    <div class="form-group">
        <button id="saveRIP" type="button" class="btn btn-primary"
                onclick="saveData('save')">Save</button>
        <button id="updateRIP" type="button"
                class="btn btn-primary" onclick="saveData('update')"
                >Update</button>
        <button id="delete" type="button" class="btn btn-danger"
        onclick="saveData('delete')">Delete</button>
        <button id="resetRIP" type="button"
                class="btn btn-danger" onclick="resetValue()" style="margin-left: 45px;">Reset</button>
    </div>
</div>

以下是完成所有工作的jQuery代码

var $select = $('#serviceNameList');
var $firstOption = $("<option/>");
$firstOption.attr("value", 0);
$firstOption.text("-Add New-");

$firstOption.on('click', function() {
    $('#name').val("");
    $('#serviceUrl').val("");
    $('#prettyUrl').val("");
    $('#redirectType').val("");

    $('#nofollow').removeAttr('checked');

    $('#saveRIP').show();
    $('#updateRIP').hide();
    $('#delete').hide();
});

$select.append($firstOption);

$(jsonResponse).each(function (index, o) {    
    var $option = $("<option/>");
    $option.attr("value", o.id);

    $option.on('click', function()  {
        $('#name').val(o.service_name);
        $('#serviceUrl').val(o.service_url);
        $('#prettyUrl').val(o.pretty_url);
        $('#redirectType').val(o.redirect_type);

        if (o.no_follow == 1)   {
            $('#nofollow').prop("checked", true);
        }
        else    {
            $('#nofollow').prop("checked", false);
        }

        $('#saveRIP').hide();

        $('#updateRIP').show();
        $('#delete').show();
    });

    $option.text(o.service_name);
    $select.append($option);
});

if ($("#serviceNameList option:selected").val() == 0)   {
    $('#saveRIP').show();

    $('#updateRIP').hide();
    $('#delete').hide();
}

这里是JSFiddle链接 - http://jsfiddle.net/6uy1quLg/5/ (尝试在Google Chrome和Firefox上运行它以查看差异)

从小提琴中可以明显看出,填充组合框的代码工作得很好, 但是对于附加click事件处理程序的代码似乎根本没有执行。

有人可以帮我解决这个问题吗? 提前致谢。


I am trying to create a specific functionality on my web page, which uses jQuery to iterate over a JSON object, populates a combo box with its values, and also attach click event handlers to the options using jQuery's .on() method.

All seemed to be working fine, until I decided to test the functionality on Google Chrome. (I had been developing on Firefox Developer Edition till now). The .on() method from jQuery does not seem to be working on Google Chrome at all.

Here is the HTML code snippet for my web page

<div id="showotherinfo">
    <div class="form-group" id="existingRedirection" style="">
        <label for="serviceNameList">Select a Pretty Redirection to edit it, or add a new one below</label>
        <select class="form-control" id="serviceNameList" name="serviceNameList">
            <option value="0">-Add New-</option>
            <option value="57">Infibeam Redirection</option>
            <option value="53">Mozilla Developers Redirection</option>
            <option value="56">SnapDeal Redirection</option>
        </select>
        <hr style="height: 1px; border: none; color: #333; background-color: #333;">                                                    
    </div>
    <div class="form-group">
        <label for="name">Service Name<font color="red" size=3>*</font></label> 
        <input class="form-control" name="name" id="name">  
    </div>
     <div class="form-group">
        <label for="serviceUrl">Target URL<font color="red" size=3>*</font></label> 
        <input class="form-control" name="serviceUrl" id="serviceUrl">
    </div>
    <label for="prettyUrl">Pretty URL<font color="red" size=3>*</font></label>
    <div class="form-inline">
        <div class="form-group">
            <input type="text" class="form-control" name="prettyUrl" id="prettyUrl" >
        </div>
    </div>
    <div class="form-group" style="margin-top: 19px;">
        <label for="redirectType">Redirect Type<font color="red" size=3>*</font></label> 
        <select class="form-control"
            name="redirectType" id="redirectType">
            <option value="0" SELECTED>-Redirection Type-</option>
            <option value="307">Temporary(307)</option>
            <option value="301">Permanent(301)</option>
            <option value="302">Found(302)</option>
        </select> 
    </div>
    <div class="checkbox">
        <label style="font-weight: bold;">
            <input type="checkbox" name="nofollow" id="nofollow">
            NoFollow this link
        </label> 
    </div>
    <div class="form-group">
        <button id="saveRIP" type="button" class="btn btn-primary"
                onclick="saveData('save')">Save</button>
        <button id="updateRIP" type="button"
                class="btn btn-primary" onclick="saveData('update')"
                >Update</button>
        <button id="delete" type="button" class="btn btn-danger"
        onclick="saveData('delete')">Delete</button>
        <button id="resetRIP" type="button"
                class="btn btn-danger" onclick="resetValue()" style="margin-left: 45px;">Reset</button>
    </div>
</div>

And here is the jQuery code that does all the work

var $select = $('#serviceNameList');
var $firstOption = $("<option/>");
$firstOption.attr("value", 0);
$firstOption.text("-Add New-");

$firstOption.on('click', function() {
    $('#name').val("");
    $('#serviceUrl').val("");
    $('#prettyUrl').val("");
    $('#redirectType').val("");

    $('#nofollow').removeAttr('checked');

    $('#saveRIP').show();
    $('#updateRIP').hide();
    $('#delete').hide();
});

$select.append($firstOption);

$(jsonResponse).each(function (index, o) {    
    var $option = $("<option/>");
    $option.attr("value", o.id);

    $option.on('click', function()  {
        $('#name').val(o.service_name);
        $('#serviceUrl').val(o.service_url);
        $('#prettyUrl').val(o.pretty_url);
        $('#redirectType').val(o.redirect_type);

        if (o.no_follow == 1)   {
            $('#nofollow').prop("checked", true);
        }
        else    {
            $('#nofollow').prop("checked", false);
        }

        $('#saveRIP').hide();

        $('#updateRIP').show();
        $('#delete').show();
    });

    $option.text(o.service_name);
    $select.append($option);
});

if ($("#serviceNameList option:selected").val() == 0)   {
    $('#saveRIP').show();

    $('#updateRIP').hide();
    $('#delete').hide();
}

And here is the JSFiddle link- http://jsfiddle.net/6uy1quLg/5/ (Try running it on both Google Chrome and Firefox to see the difference)

As is evident from the fiddle, the code to populate the combo box is working just fine, but to code to attach click event handler doesn't seem to be executing at all.

Can anybody please help me out regarding this?? Thanks in advance.


原文:https://stackoverflow.com/questions/29507364
更新时间:2022-04-02 06:04

最满意答案

我正在使用下面的代码,它对我来说工作正常。我也在Web API中使用它来以字符串形式返回View。

对于更多,你可以创建静态类 ,并使下面的方法静态。

 public string RenderPartialView(string controllerName, string viewName, object model = null) {
     System.Web.HttpContextBase contextBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);

     var routeData = new RouteData();
     routeData.Values.Add("controller", controllerName);
     var controllerContext = new System.Web.Mvc.ControllerContext(contextBase, routeData,
      new EmptyController());

     var razorViewEngine = new System.Web.Mvc.RazorViewEngine();
     var razorViewResult = razorViewEngine.FindPartialView(controllerContext, viewName, false);

     var writer = new StringWriter();
     System.Web.Mvc.ViewContext viewContext;


     viewContext = new System.Web.Mvc.ViewContext(controllerContext, razorViewResult.View,
      new System.Web.Mvc.ViewDataDictionary(model), new System.Web.Mvc.TempDataDictionary(), writer);

     viewContext.ViewData["controller"] = controllerName;

     HttpContext.Current.Items.Add("controller", controllerName);

     razorViewResult.View.Render(viewContext, writer);

     string htmlString = writer.ToString();
     writer.Dispose();

     return htmlString;
    }

private class EmptyController: System.Web.Mvc.ControllerBase {
  protected override void ExecuteCore() {}
 }

现在请找到我们如何从控制器调用它的例子。

RenderPartialView("Home", string.Format("~/Views/Home/{0}.cshtml", "Index"));

我希望这对你有用。


I am using below code and it is working fine for me.i am also using it in Web API for returning View in form of string.

For more you can create Static Class and make below method static.

 public string RenderPartialView(string controllerName, string viewName, object model = null) {
     System.Web.HttpContextBase contextBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);

     var routeData = new RouteData();
     routeData.Values.Add("controller", controllerName);
     var controllerContext = new System.Web.Mvc.ControllerContext(contextBase, routeData,
      new EmptyController());

     var razorViewEngine = new System.Web.Mvc.RazorViewEngine();
     var razorViewResult = razorViewEngine.FindPartialView(controllerContext, viewName, false);

     var writer = new StringWriter();
     System.Web.Mvc.ViewContext viewContext;


     viewContext = new System.Web.Mvc.ViewContext(controllerContext, razorViewResult.View,
      new System.Web.Mvc.ViewDataDictionary(model), new System.Web.Mvc.TempDataDictionary(), writer);

     viewContext.ViewData["controller"] = controllerName;

     HttpContext.Current.Items.Add("controller", controllerName);

     razorViewResult.View.Render(viewContext, writer);

     string htmlString = writer.ToString();
     writer.Dispose();

     return htmlString;
    }

private class EmptyController: System.Web.Mvc.ControllerBase {
  protected override void ExecuteCore() {}
 }

Now please find example how we can call it from controller.

RenderPartialView("Home", string.Format("~/Views/Home/{0}.cshtml", "Index"));

I hope this will be useful to you.

相关问答

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)