简体   繁体   中英

onclick div colour should change

Am having several boxes(more than 100) that will create dynamically with

<div id="window5"></div>
<div id="window18"></div>
<div id="window190"></div>

Now If i click on one box the colour should be red,then if i click on the other box the colour should be changed to red(the first box colour should come to normal).I used some code like this,but it is not taking the css class.

How can i get the dynmic id of this case.

css file:

.selected{ color: red; }

used javasscript code as;

    <script type="text/javascript">

        $(document).ready(function () {

            $("div[id *= 'window']").click(function (e) {

                $(".selected").removeClass("selected");
                $(this).addClass("selected");
                e.stopPropagation();
            });
            $(document).click(function () {
                $(".selected").removeClass("selected");
            });
        });

    </script>

That's because they are generated. You have to use the .on statement.

 $("div[id *= 'window']").on('click', function (e) {

If you're using a version of jQuery older than 1.7 please use .live() instead:

 $("div[id *= 'window']").live('click', function (e) {

You will have to use jquery's .live or .on because you generate divs dynamically.

To change background color of the divs, you'll have to use 'background-color' in css instead of 'color'.

http://jsfiddle.net/fFcua/

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