jquery选择器不适用于循环输出的动态内容

时间:2016-10-29 12:23:13

标签: jquery

我已经设置了一个输出动态内容的for循环,但它没有选择一些特定的类,就像你在for循环下面的jQuery部分中看到的那样。但是这个选择器不起作用。如果我直接选择类,它会添加这个选择器,它将不再起作用。谁知道如何在jQuery中解决这个问题?

function renderSmartphones() {
  var newContent = "";
  for(var i = 0; i < smartphones.length; i++) {
    newContent += "<div class='col-lg-4 col-md-4 col-sm-4 col-xs-12 box item'>";
    newContent += "<div class='rom'>" + smartphones[i].rom + "</div>";
    newContent += '<img src="' + smartphones[i].image + '" ';
    newContent += "class='image'";
    newContent += "alt='" + smartphones[i].alt_image + "' />";
    newContent += "<button class='add-to-cart' type='button'>" + "add to cart" + "</button>";
    newContent += "</div>";
  }
  $("#mobile").html(newContent);
}


$(document).on("click", ".add-to-cart", function() {
    $(this).parent(".rom").find("img").css("border", "1px solid red);
	$(this).find(".item").css("border", "1px solid red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
	<div id="wrapper">
		<span><i id="shopping-cart" alt="shopping-cart-icon"></i></span>
		
		<div id="mobile"></div>
	</div>
</body>

1 个答案:

答案 0 :(得分:0)

你的选择器和委托事件处理程序工作正常;主要问题是你的DOM遍历。 button不是.item的父级,因此find()无效。另请注意,您应该在外部CSS文件中定义样式,并根据需要添加/删除类。添加内联CSS是个坏主意。最后,由于引号不一致,您的字符串连接被破坏了。试试这个固定版本:

var smartphones = [{
  rom: 'rom1',
  image: 'image1.jpg',
  alt_image: 'alt_image1.jpg'
}, {
  rom: 'rom2',
  image: 'image2.jpg',
  alt_image: 'alt_image2.jpg'
}];

function renderSmartphones() {
  var newContent = "";
  for (var i = 0; i < smartphones.length; i++) {
    newContent += '<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 box item">';
    newContent += '<div class="rom">' + smartphones[i].rom + '</div>';
    newContent += '<img src="' + smartphones[i].image + '" class="image" alt="' + smartphones[i].alt_image + '" />';
    newContent += '<button class="add-to-cart" type="button">add to cart</button>';
    newContent += '</div>';
  }
  $("#mobile").html(newContent);
}

$(document).on("click", ".add-to-cart", function() {
  $(this).closest(".item").addClass('active').find("img").addClass('active');
});

renderSmartphones();
.active {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="wrapper">
    <span><i id="shopping-cart" alt="shopping-cart-icon"></i></span>

    <div id="mobile"></div>
  </div>
</body>

相关问题