Problem with events in jquery

I do not know if this name explains this situation well. Below is the code I wrote to create div elements when a button is clicked. Then, by clicking on any of the created divs, we can change the background of the div by selecting a color from the drop-down list. However, if I click on another div and try to change the color by choosing a different color from the drop-down list, the previously pressed divs will also suffer from the new color. Why is this happening. I want the selected div to change color without affecting previously pressed divs. I read the thread highlighting on this site, some of which talk about loose clicks, but I can’t solve the problem. Thanks for the help.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 

<style> 
.aaa { width:100px; height:100px;background-color:#ccc;margin-bottom:5px;}
p{widht:500px; height:500px; margin:0px; padding:0px;border:2px solid red;color:#000;}
</style>

<select id="item_select" name="item"> 
    <option value="1">red</option> 
    <option value="2">blue</option> 
    <option value="3">green</option> 
</select>

<button>Click to create divs</button>
<p id="ptest"></p>


<script type="text/javascript">
var dividcount = 1;
$("button").click(run);
function run(){
 var myDiv = $('<div id=lar'+dividcount+' class=aaa></div>');
 $(myDiv).clone().appendTo('#ptest');
 $(dividcount++);
 $("div").bind('click',(function() {
  var box = $("div").index(this);
  var idd = (this.id);
  $("#"+idd).text("div #"+idd);
  $("select").change(function(){
   var str= $("select option:selected").text();
   $("#"+idd).css("background-color",str);
  });
 }));
}; 
</script>
+3
source share
3 answers

:

$("select").change(function(){
   var str= $("select option:selected").text();
   $("#"+idd).css("background-color",str);
});

:

$(this).find("select").change(function()
    var str= $(this).find("option:selected").text();
    $("#"+ idd ).css("background-color",str);
});

, , , , div, . , .

0

: http://jsfiddle.net/fUHFp/1/ ( , )

:

$("div").bind('click',(function() { 
    // ...

click div button.

, .

:

$("div").bind('click',(function() {
  var box = $("div").index(this);
  var idd = (this.id);
  // ...

:

myDiv.bind('click',(function() {
  var box = $("div").index(this);
  var idd = (this.id);
  // ...

<div>.

change(), click, @karim79.

, :

$(dividcount++);

... . jQuery.

:

dividcount++;

, <div>, . myDiv jQuery, .

, :

 $(myDiv).clone().appendTo('#ptest');

... :

 myDiv.appendTo('#ptest');

EDIT: .change(), , div <select>. , .

divs aaa change(), .

, change run() :

$("select").change(function(){
   var str= $(this).find("option:selected").text();
   $(".aaa").css("background-color",str);
});

, , click(). this jQuery.

, :

$("#"+idd).text("div #"+idd);

:

$(this).text("div #"+idd);
0
source

Source: https://habr.com/ru/post/1783155/


All Articles