Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 查询在单击时注册失败_Javascript_Jquery_Html - Fatal编程技术网

Javascript 查询在单击时注册失败

Javascript 查询在单击时注册失败,javascript,jquery,html,Javascript,Jquery,Html,这是一个简单明了的问题,我不知道到底是什么问题。基本上,我得到的是一个简单的查询,每次单击x时注册一个函数,但是,.click查询由于未知原因从未注册 $(".char-outfit-list .cell").click(function() { // register ever click to a cell $(".char-outfit img").attr("src", $("img", this).attr("src") // set the main image to

这是一个简单明了的问题,我不知道到底是什么问题。基本上,我得到的是一个简单的查询,每次单击x时注册一个函数,但是,
.click
查询由于未知原因从未注册

$(".char-outfit-list .cell").click(function() { // register ever click to a cell
  $(".char-outfit img").attr("src",
    $("img", this).attr("src")  // set the main image to the cell image source
   );
});
这些单元格也由脚本动态追加:

$(".char-outfit-list").append('<div class="cell"><img src="/assets/images/skins/' + id + '.png"></div>');
$(“.char装备列表”).append(“”);

主要问题在于单击处理程序的工作方式。因为执行时,
.click
会运行,所以实际上可能没有挂接到任何东西

您应该坚持在jQuery中执行所有操作:

let img = $('<img />').attr('src', `/assets/images/skins/${id}.png`);
// Create the cell, AND attach the handler
// $('<div class="cell" />') also works here
let cell = $('<div />')
  .addClass('cell')
  .append(img)
  .click(function() { // register ever click to a cell
    $(".char-outfit img").attr("src",
      $("img", this).attr("src")  // set the main image to the cell image source
    );
  });
// Append the cell with the attached handler
$(".char-outfit-list").append(cell);

在执行第一个代码段时,元素是否已经存在?如果不是,选择器将返回一个空结果集,并且不会注册任何单击侦听器。只要更改了
选项,就会添加元素(列表元素被清除,如果其数据信息符合
选项,则会再次追加它们。因此,第一个代码段在单元格存在之前执行。
$(".char-outfit-list").on('click', '.cell', function() { // register ever click to a cell
  $(".char-outfit img").attr("src",
    $("img", this).attr("src")  // set the main image to the cell image source
   );
});