简体   繁体   中英

How to stop jQuery plugin in specific page?

I have a web application which uses MVC layouts, all of my views inherits from this page, in layout page I am using a jquery plug in (iCheck), now I have a page which also inherits from my layout but I don't want this page to use that plugin, in layout I have this script:

<script>
    $(function() {
        $('input').iCheck();
    });
</script>

Now Is there any way to tell jQuery not use this plugin in that page?

One way is this:

In layout replace the script code with this:

@{
  bool? dontICheck = ViewBag.dontICheck;
}
if(!dontICheck.getValueOrDefault()){
<script>
    $(function() {
        $('input').iCheck();
    });
</script>
}

This means iCheck will work at default. If you dont want it to work add this line into the view's action method which you dont want to use iCheck:

ViewBag.dontICheck = true;

A simple method is to add a class where you do not want this applied, eg:

<input class='noicheck' ...

then apply this in your selector:

$("input:not(.noicheck)").iCheck();

This will then work across your entire site without needing page-by-page changes or any changes to your viewmodel / viewbag etc and will still allow some controls to have this check applied.

I assume that your page has some specific class for styling (for example "special-page").

You can use that to identify that you are on that page and not to init jQuery plugin.

replace

$('input').iCheck();

with

if(!$(".special-page").length){
   $('input').iCheck();
}

Replace the current script block you have with:

@if (IsSectionDefined("iCheck")) {
    RenderSection("iCheck");
}
else { 
    <script>
        $(function() {
            $('input').iCheck();
        });
    </script>
}

Then in the view that you don't want this run, add:

@section iCheck {}

By defining the section, the layout will include the contents of the section, rather than the default code (your iCheck script), which will just be empty because nothing was provided within the curly brackets.

The better approach instead of relying in viewbags and other server side codes is to use class in the elements as it's more clear what's the intention of the code. Here's an example.

<input class="not-icheck" value="I'm a rebel!" />
...
<script>
    $(function()
    {
        $('input:not(.not-icheck)').iCheck();
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM