如何使用jQuery将4个4元素追加到另一个div中

时间:2017-05-16 20:13:20

标签: javascript jquery object append

你好我是一名学习jQuery的学生,我的目标是将元素(只是那个单个字符)移动到指定的##;#selected' div区域和剩下的区域(因为我将在此步骤之后添加第二个选择选项)。但是,当单击其中一个字符时,所有字符都会移动到“#selected' DIV。我知道我的代码是错误的和未完成的,但我只是不确定如何修复它或如何拆分元素因为它们都具有相同的类。感谢您提供任何帮助或提示,我非常感谢。

JS:

$(document).ready(function() {

//Audio
// var audioElement = $('audio');
//  audioElement.attr('src', 'assets/mp3/cantina.mp3');
//  audioElement.attr('autoplay', 'autoplay');
//  audioElement.loop = true; 

//Objects
var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/hansolo.jpg",
}

var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/chewy.jpg",
}

var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/jabba.jpg",
}

var greedo = {
    name: "Greedo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/greedo.jpg",
}

var choices = [hansolo, chewy, jabba, greedo];

var charOptionsRow = $('#charOptions');
    $.each(choices, function(index, choice) {
      // Create a new div.col-lg-3 to be appended to row.
      var charOptionCol = $('<div>')
        .addClass('char-option col-lg-3');

      // Append image to col.
      var charImg = $('<img>')
        .addClass('char-img')
        .attr('src', choice.src);
      charOptionCol.append(charImg);

      // Append text to col.
      var charText = $('<h3>')
        .addClass('char-text')
        .text(choice.name);
      charOptionCol.append(charText);

      // Append column to row.
      charOptionsRow.append(charOptionCol);
});

$(document).on('click', '.char-img', 'char-text', function() {
    if (hansolo) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
    if (chewy) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
    if (jabba) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
    if (greedo) {
        var charPick =$("#chosen");
        $('.char-img').appendTo(charPick);
        $('.char-text').appendTo(charPick);
    }
});
});

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>JQuery Game</title>

        <link rel="stylesheet" type="text/css" href="assets/css/reset.css">
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="assets/css/style.css">
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
    </head>
<body>

    <div class="container" style="max-width:800px;">
        <h1 align="center">Star Wars Game</h1>
        <h2 align="center" id="character-text">Choose your character:</h2>
        <div class="row" id="charOptions" style="max-width:800px;" align="center">
        </div>

        <div class="row" align="center" style="max-width:800px;">
            <!-- Choice Header -->
            <div class="col-lg-6 you" id="chosen" align="center">
                <h2 align="center" id="chosen-text" class="hidden">You</h2>
            </div>
            <!-- First Enemy Header -->
            <div class="col-lg-6 fighting" align="center">
                <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
            </div>
        </div>
        <div class="row" align="center" style="max-width:800px;">
            <!-- Enemies Header-->
            <div class="col-lg-12" id="enemies" align="center">
                <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
            </div>
        </div>  
            <div class="row" align="center" style="max-width:800px;">
            <!-- Enemies -->
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
                    <div id="first-enemy"></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
                    <div id="second-enemy"></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
                    <div id="third-enemy"></div>
                </div>
            </div>

    </div>

<script src="assets/js/game.js"></script>
</body>

4 个答案:

答案 0 :(得分:1)

您一次移动所有char-imgchar-text项目(除了一些拼写错误) - 对$('.char-img')的引用并不知道您的意思是被点击的那个。

相反,请使用this告诉您单击了哪个元素。然后,抓住相邻的文本或图像,然后移动 那两个。

$(document).on('click', '.char-img, .char-text', function() {
  var el = $(this),
      img, txt;

  if (el.hasClass('char-img')) {
    img = el;
    txt = el.next('.char-text');
  } else {
    txt = el;
    img = el.prev('.char-img');
  }

  $('#chosen').append(img).append(txt);
});

&#13;
&#13;
$(document).ready(function() {

  //Objects
  var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/hansolo.jpg",
  }

  var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/chewy.jpg",
  }

  var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/jabba.jpg",
  }

  var greedo = {
    name: "Greedo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "assets/images/greedo.jpg",
  }

  var choices = [hansolo, chewy, jabba, greedo];

  var charOptionsRow = $('#charOptions');
  $.each(choices, function(index, choice) {
    // Create a new div.col-lg-3 to be appended to row.
    var charOptionCol = $('<div>')
      .addClass('char-option col-lg-3');

    // Append image to col.
    var charImg = $('<img>')
      .addClass('char-img')
      .attr('src', choice.src);
    charOptionCol.append(charImg);

    // Append text to col.
    var charText = $('<h3>')
      .addClass('char-text')
      .text(choice.name);
    charOptionCol.append(charText);

    // Append column to row.
    charOptionsRow.append(charOptionCol);
  });

  $(document).on('click', '.char-img, .char-text', function() {
    var el = $(this),
      img, txt;
      
    if (el.hasClass('char-img')) {
      img = el;
      txt = el.next('.char-text');
    } else {
      txt = el;
      img = el.prev('.char-img');
    }

    $('#chosen').append(img).append(txt);
  });
});
&#13;
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

<div class="container" style="max-width:800px;">
  <h1 align="center">Star Wars Game</h1>
  <h2 align="center" id="character-text">Choose your character:</h2>
  <div class="row" id="charOptions" style="max-width:800px;" align="center">
  </div>

  <div class="row" align="center" style="max-width:800px;">
    <!-- Choice Header -->
    <div class="col-lg-6 you" id="chosen" align="center">
      <h2 align="center" id="chosen-text" class="hidden">You</h2>
    </div>
    <!-- First Enemy Header -->
    <div class="col-lg-6 fighting" align="center">
      <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
    </div>
  </div>
  <div class="row" align="center" style="max-width:800px;">
    <!-- Enemies Header-->
    <div class="col-lg-12" id="enemies" align="center">
      <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
    </div>
  </div>
  <div class="row" align="center" style="max-width:800px;">
    <!-- Enemies -->
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
      <div id="first-enemy"></div>
    </div>
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
      <div id="second-enemy"></div>
    </div>
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
      <div id="third-enemy"></div>
    </div>
  </div>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

而不是听“$(document).on(...”,听取$(“。char-option”)。on(“click”,function().... - 然后,在里面函数,$(this)将是被点击的元素。这将允许您仅在具有“char-option”类的元素上侦听单击事件,而不是在任何地方侦听单击事件。

在if语句中,所有这些都将解析为true。我理解的意图是“如果点击hansolo然后”,但你真的在问“hansolo是不是未定义”。

虽然我没有为您提供一切,但希望这有助于您指明正确的方向。

答案 2 :(得分:0)

在点击事件中,请尝试使用$('.char-img'),而不是使用$(this)选择器。

此外,如果您要在每个if声明中运行同一段代码,则无需检查被选中的人。

看看这是否适合你。

&#13;
&#13;
$(document).ready(function() {

  //Audio
  // var audioElement = $('audio');
  //  audioElement.attr('src', 'assets/mp3/cantina.mp3');
  //  audioElement.attr('autoplay', 'autoplay');
  //  audioElement.loop = true; 

  //Objects
  var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/7b72d15a85bf468d8af9c5b5699e02ca.png",
  };

  var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/044c70c30f084ba095c35aa7e4451f0c.png",
  };

  var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/458ccfc9819f4f8b85116b81584f4eea.png",
  };

  var boba = {
    name: "Boba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/85458d08609f4170b5b8cdda58fca07c.png",
  };

  var choices = [hansolo, chewy, jabba, boba];

  var charOptionsRow = $('#charOptions');
  $.each(choices, function(index, choice) {
    // Create a new div.col-lg-3 to be appended to row.
    var charOptionCol = $('<div>')
      .addClass('char-option col-lg-3');

    // Append image to col.
    var charImg = $('<img>')
      .addClass('char-img')
      .attr('src', choice.src);
    charOptionCol.append(charImg);

    // Append text to col.
    var charText = $('<h3>')
      .addClass('char-text')
      .text(choice.name);
    charOptionCol.append(charText);

    // Append column to row.
    charOptionsRow.append(charOptionCol);
  });

  $('.char-option').on('click', function() {
    var $charPick = $("#chosen");
    var $chosen = $('#chosen-text');
    var $img = $(this).find('img').clone();
    var $header = $(this).find('h3').clone();
    var name = $header.text();

    $chosen.children('span').html(name);
    $chosen.removeClass('hidden');

    $charPick.find('img').remove();
    $charPick.find('h3').remove();
    $charPick.append($img).append($header);

    $('html, body').animate({
      scrollTop: $(document).height()
    });
  });
});
&#13;
#chosen .char-img {
   border: 0.2em solid black;
}
&#13;
<head>
  <meta charset="UTF-8">
  <title>JQuery Game</title>
  <link rel="stylesheet" type="text/css" href="assets/css/reset.css">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="assets/css/style.css">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body>
  <div class="container" style="max-width:800px;">
    <h1 align="center">Star Wars Game</h1>
    <h2 align="center" id="character-text">Choose your character:</h2>
    <div class="row" id="charOptions" style="max-width:800px;" align="center">
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Choice Header -->
      <div class="col-lg-6 you" id="chosen" align="center">
        <h2 align="center" id="chosen-text" class="hidden">You've chosen <span class="chosen-name"></span></h2>
      </div>
      <!-- First Enemy Header -->
      <div class="col-lg-6 fighting" align="center">
        <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies Header-->
      <div class="col-lg-12" id="enemies" align="center">
        <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies -->
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="first-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="second-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="third-enemy"></div>
      </div>
    </div>
  </div>
</body>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
$(document).ready(function() {

  //Audio
  // var audioElement = $('audio');
  //  audioElement.attr('src', 'assets/mp3/cantina.mp3');
  //  audioElement.attr('autoplay', 'autoplay');
  //  audioElement.loop = true; 

  //Objects
  var hansolo = {
    name: "Han Solo",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/7b72d15a85bf468d8af9c5b5699e02ca.png",
  };

  var chewy = {
    name: "Chewy",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/044c70c30f084ba095c35aa7e4451f0c.png",
  };

  var jabba = {
    name: "Jabba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/458ccfc9819f4f8b85116b81584f4eea.png",
  };

  var boba = {
    name: "Boba",
    attack: 10,
    hp: 20,
    counter: 0,
    src: "https://image.prntscr.com/image/85458d08609f4170b5b8cdda58fca07c.png",
  };

  var choices = [hansolo, chewy, jabba, boba];

  var charOptionsRow = $('#charOptions');
  $.each(choices, function(index, choice) {
    // Create a new div.col-lg-3 to be appended to row.
    var charOptionCol = $('<div>')
      .addClass('char-option col-lg-3');

    // Append image to col.
    var charImg = $('<img>')
      .addClass('char-img')
      .attr('src', choice.src);
    charOptionCol.append(charImg);

    // Append text to col.
    var charText = $('<h3>')
      .addClass('char-text')
      .text(choice.name);
    charOptionCol.append(charText);

    // Append column to row.
    charOptionsRow.append(charOptionCol);
  });

  $('.char-img, .char-text').on('click', function() {
    $('#chosen-img').remove();
    $('#chosen').prepend('<img id="chosen-img"/>');
    $('#chosen-img').css({
      'border': '2px solid red'
    }).attr('src', $(this).parent().find('img').attr('src'));
    $('h2', '#chosen').text("You Choose: " + $(this).parent().find('.char-text').text()).removeClass('hidden').show();
    $("html, body").animate({
      scrollTop: $(document).height()
    }, 100);
    //console.log($(this).attr('src'));
    // console.log($(this).parent().find('.char-text').text());
  });
});
&#13;
<head>
  <meta charset="UTF-8">
  <title>JQuery Game</title>
  <link rel="stylesheet" type="text/css" href="assets/css/reset.css">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="assets/css/style.css">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body>
  <div class="container" style="max-width:800px;">
    <h1 align="center">Star Wars Game</h1>
    <h2 align="center" id="character-text">Choose your character:</h2>
    <div class="row" id="charOptions" style="max-width:800px;" align="center">
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Choice Header -->
      <div class="col-lg-6 you" id="chosen" align="center">
        <h2 align="center" id="chosen-text" class="hidden">You</h2>
      </div>
      <!-- First Enemy Header -->
      <div class="col-lg-6 fighting" align="center">
        <h2 align="center" id="chosen-text" class="hidden">Fighting</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies Header-->
      <div class="col-lg-12" id="enemies" align="center">
        <h2 align="center" id="enemies-text" class="hidden">Your Enemies</h2>
      </div>
    </div>
    <div class="row" align="center" style="max-width:800px;">
      <!-- Enemies -->
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="first-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="second-enemy"></div>
      </div>
      <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" align="center">
        <div id="third-enemy"></div>
      </div>
    </div>
  </div>
</body>
&#13;
&#13;
&#13;