简体   繁体   中英

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). However, when one of the characters is clicked, all of the characters move to that '#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:

$(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>

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.

Instead, use this to tell you which element was clicked. 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.

In your if statement, all of those will resolve to true. I understand the intent is "if hansolo was clicked then", but you're really asking "if hansolo is not undefined".

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) .

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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