开发者

jQuery: Apply css to image on click event

开发者 https://www.devze.com 2023-01-01 01:06 出处:网络
I want basically the same as jquery select image a row of images that you can select one of. But I\'m trying to style the one I select, and store it.

I want basically the same as jquery select image

a row of images that you can select one of.

But I'm trying to style the one I select, and store it.

var selectedicon = "";

function selecticon(){

$('#iconselect').children().click(function(){
        $(".selectedicon").removeclass("selectedicon");
        selectedicon = $(this).attr("src");
        $(this).addclass("selectedicon");
    });
}
开发者_开发问答

on this

  <div id="iconselect">
    <img src="/red-dot.png" class="selectedicon" />
    <img src="/green-dot.png" />
    <img src="/blue-dot.png" />
    <img src="/orange-dot.png" />
</div>

What am I doing wrong?


jQuery addClass and removeClass are mistyped (C should be capital).

Is the function selecticon called at all?


As you are not saying what does not work, here is a wild guess:

Probably the function selection() is never called and thus the click handler is never attached to the elements. Put your code into the document.ready callback instead:

var selectedicon = "";

$(function() {
    // I would use $('#iconselect img').click(...)
    $('#iconselect').children().click(function(){
        $(".selectedicon").removeClass("selectedicon");
        selectedicon = $(this).attr("src");
        $(this).addClass("selectedicon");
    });
});

This ensures that your code is executed once the DOM is loaded.

You also have some typos in the method names:

  • removeclass() must be removeClass()
  • addclass() must be addClass()
0

精彩评论

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