开发者

Enable/Disable an image link depending on the state of the checkbox in jquery

开发者 https://www.devze.com 2023-03-31 08:37 出处:网络
I built a jquery plugin to which I\'m passing the ID of an HTML checkbox as a parameter: $(\"div.plugin\").pluginname({

I built a jquery plugin to which I'm passing the ID of an HTML checkbox as a parameter:

$("div.plugin").pluginname({
      chckBoxID: "chk" + $(this).attr("id")
});

The plugin generates an image link

(function( $ ){ 

    $.fn.extend({   

        pluginname: function(options){

            var defaults = {
                chckBoxID: ""
            }
            var options = $.extend(defaults, options);
            var o = options;
            $("div#" + imageDiv).html("<a><img src='images/x.gif'></img></a>");
        }
    });
});

By default, the checkbox is not checked.

What I want to do is:

(1) When the user clicks/checks the checkbox, the image link should open a new browser window.

(2) When the user unchecks the checkbox, the image link should not open a new browser window.

Your help is appreciated.

An update to my code ---

HTML Code looks like this

<div>
    <input type="checkbox" id开发者_如何学JAVA="chk1" />
</div>
<div class="plugin" id="1"></div>

<a><img> is generated by the plugin

$(this).html("<a><img src='images/x.gif'></img></a>");


You can't use $(this) the way you're passing it into the plugin. You CAN do something like this though:

$("div.plugin").each(function (i) {
    $(this).pluginname({
      chckBoxID: "chk" + $(this).attr("id")
    });
});

Then I believe what you're trying to do in your plugin is something like this:

(function ($) {
    $.fn.pluginname = function (options) {
        var opts = $.extend({}, $.fn.pluginname.defaults, options);

        var pluginnameClick = function (e) {
            if ($("#" + opts.chckBoxID).is(":checked")) {
                e.preventDefault();
                window.open($(this).attr('href'));
            }
        };

        $(this).each(function (i) {
            $('a', $(this)).bind("click", pluginnameClick);
        });
    };

    $.fn.pluginname.defaults = {
        chckBoxID: "chk"
    }
})(jQuery);

This assumes your HTML code looks something like this:

<div class="plugin" id="1">
    <a href="link1.htm"><img src="image.jpg" /></a>
    <input type="checkbox" id="chk1" />
</div>
<div class="plugin" id="2">
    <a href="link2.htm"><img src="image.jpg" /></a>
    <input type="checkbox" id="chk2" />
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消