简体   繁体   English

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

[英]how to append just 1 element of 4 to another div using jQuery

Hello I am a student learning jQuery and my goal is to move the element (just that single character) clicked to a specified '#chosen' div area and the rest to remain (as I will be adding a second selecting option after this step). 您好我是一名学习jQuery的学生,我的目标是将元素(只是那个单个字符)移动到指定的'#chosen'div区域,其余部分保留(因为我将在此步骤后添加第二个选择选项) 。 However, when one of the characters is clicked, all of the characters move to that '#chosen' div. 但是,当单击其中一个字符时,所有字符都移动到'#chosen'div。 I know my code is wrong and unfinished, but I am just unsure how to fix it or how to split up the elements because they all have the same class. 我知道我的代码是错误的和未完成的,但我只是不确定如何修复它或如何拆分元素因为它们都具有相同的类。 Thank you for any help or hints in advanced I really appreciate it. 感谢您提供任何帮助或提示,我非常感谢。

JS: 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: 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>

You're moving all the char-img and char-text items (barring a few typos) at once -- references to $('.char-img') don't know that you mean just the one that was clicked. 你正在移动所有的char-imgchar-text项目(除了一些拼写错误) - 对$('.char-img')引用并不知道你的意思只是被点击的那个。

Instead, use this to tell you which element was clicked. 相反,使用this来告诉您单击了哪个元素。 Then, grab the adjacent text or image, and move just those two. 然后,抢在相邻的文本或图像,并移动只是这两个。

$(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);
});

 $(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); }); }); 
 <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> 

Instead of listening for "$(document).on(...", listen for $(".char-option").on("click", function() .... - then, inside the function, $(this) will be the element that was clicked on. Instead of listening for a click anywhere, this will allow you to listen for click events just on elements that have the "char-option" class. 而不是听“$(document).on(...”,监听$(“。char-option”)。on(“click”,function().... - 然后,在函数内部,$ (这)将是被点击的元素。这将允许您仅在具有“char-option”类的元素上侦听单击事件,而不是在任何地方监听单击。

In your if statement, all of those will resolve to true. 在if语句中,所有这些都将解析为true。 I understand the intent is "if hansolo was clicked then", but you're really asking "if hansolo is not undefined". 我理解意图是“如果点击hansolo然后”,但你真的在问“hansolo是不是未定义”。

While I haven't provided everything for you, hopefully this will help get you pointed in the right direction. 虽然我没有为您提供一切,但希望这有助于您指出正确的方向。

In the click event, instead of using $('.char-img') selector, try using $(this) . 在click事件中,不要使用$('.char-img')选择器,而是尝试使用$(this)

Also, you don't need to check who was chosen if you're going to run the same piece of code in every if statement. 此外,如果要在每个if语句中运行相同的代码, if无需检查选择的对象。

See if this works for you. 看看这是否适合你。

 $(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() }); }); }); 
 #chosen .char-img { border: 0.2em solid black; } 
 <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> 

 $(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()); }); }); 
 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM