【问题标题】:How to extract a sibling img element based off the greatest input[type="number"] value如何根据最大 input[type="number"] 值提取兄弟 img 元素
【发布时间】:2018-03-03 03:23:03
【问题描述】:

我有一个无序列表,每个 li 元素都有一个图像和一个兄弟输入[type="number"](IMG - #),我试图将图像附加到具有最高数字 val() 的兄弟,当单击了一个按钮... $('#guessCheck')

我的 html 代码看起来像这样

 <div id="checkedImageContainer" class="hidden col-md-4">
                <div class="text-center">
                    <h3 style="color:black"><strong>Now rate your favorite Images!!(#1-10)</strong></h3>
                    <ul class="checkedImageList">
<li><image src="pics/hammer.jpg" name="hammer"><input id="rateInput" type="number" value="1" min="1" max="10"><label id="RateButton">Rate</label></li>
<li><image src="pics/hardhat.jpg" name="hardhat"><input id="rateInput" type="number" value="1" min="1" max="10"><label id="RateButton">Rate</label></li>
<li><image src="pics/paintbrush.jpg" name="paintbrush"" name="hammer"><input id="rateInput" type="number" value="1" min="1" max="10"><label id="RateButton">Rate</label></li>
                    </ul>
                    <button id="guessCheck">That's MY Opini0n</button>
                </div>
<ul id="highestRated">
</ul>
</div>

到目前为止,我的 jquery 中有这个,但我的代码中出现了 FOR MY IMAGE 的语法错误,我知道 src attr 是错误的...

$('#guessCheck').on('click', function(){

let highestRating = $("input[type='number']").map(function() {
     return {ele: $(this), val: parseFloat(this.value)};
 }).get().sort((a,b) => {return b.val - a.val;})[0].ele;
 $('#guessImageContainer').removeClass('hidden');
 console.log('removed hidden class on the #highestrated list');
 $('#guessImageContainer').append('<li><img src="' + highestRating.closest('img').attr('src') + '"><input id="guessMyValue" type="text"><button class="text-center" id="finishButton">Finish_Button</button><h2 class="text-center">Now Guess The Name Of The image</h2></li>');

});

在这种情况下,我想附加 HAMMER img //\

这是完整的游戏板,以及从“那是我的意见”按钮附加图像时我遇到的问题///

【问题讨论】:

  • 可能想首先将您的代码更改为input[type='text'] 为input[type='number']。看看你离得有多近。

标签: jquery html


【解决方案1】:

你的代码有一些错误:

  • ID 必须是唯一的。将它们更改为类。
  • 必须将选择器按属性更改为 [type='number']
  • 正确打开和关闭字符串
  • 对地图结果进行排序
  • 您需要 prev 而不是 closest
  • 不要在事件处理程序中添加事件处理程序
  • 正确委派您的活动

更新后的小提琴是here。

var maxCheckedNum = 3;
$(document).ready(function () {
    // MAKE SURE YOUR USER WAS BORN BEFORE 2000
    //Once that is confirmed you can remove the class hidden
    $('#birthYear').on('click', function (e) {
        let userAge = $('#usersInput').val();
        if (userAge.trim() == '') {
            return;
        }
        if (+userAge <= 1999) {
            maxCheckedNum = +userAge;
            $('#gameRules').removeClass('hidden');
            $('#ageID').hide();

            $("input[type=checkbox]:not(:checked)").attr("disabled", $("input[type=checkbox]:checked").length >= maxCheckedNum);
            /*
             THIS LINES ARE USELESS
             $('div>p').attr('id', "highlight");
             let userAgesLog = [];
             userAgesLog.push(+userAge);
             */
        }
        else if (+userAge >= 2000) {
            alert("You are of not of the age requirement to play this game")
        }
    });


    //Only allow users to check 3 models
    $('#imageNinpputList input[type=checkbox]').on('change', function (e) {
        $("input[type=checkbox]:not(:checked)").attr("disabled", $("input[type=checkbox]:checked").length >= maxCheckedNum);
    })

    //Push checked images to the second div when the confirm button is clicked
    $('#confirm').on('click', function (e) {
        $('#checkedImageContainer').removeClass('hidden');
        $('#third-rule').removeClass('hidden');
        $(this).prop('disabled', true);
        $('#imageNinpputList input[type="checkbox"]:checked').each(function (idx, ele) {
            $('.checkedImageList').append('<li><img src="' + $(this).prev('img').attr('src') +
                    '"><input data-old-value="1" class="rateInput" type="number" value="1" min="1" max="10">' +
                    '<label id="RateButton">Rate</label></li>');
        });
    });
    // When input number is changed, loop through the other inputs and disallow them from being the same value as 'this input'

    //
    // delegate event on parent
    //
    $('.container').on('input', '#checkedImageContainer input[type=number]', function (e) {
        if ($('#checkedImageContainer input[type=number]').not(this).map(function () {
                    return $(this).val();
                }).get().indexOf($(this).val()) >= 0) {
            $(this).val(this.dataset.oldValue);
        } else {
            this.dataset.oldValue = this.value;
        }
    });


    $('#guessCheck').on('click', function () {
        //
        // chose the right inputs
        //
        let highestRating = $('#checkedImageContainer input[type=number]').map(function () {
            return {ele: $(this), val: parseFloat(this.value)};
        }).get().sort(function (a, b) {
            return b.val - a.val;
        })[0].ele;
        $('#guessImageContainer').removeClass('hidden');
        console.log('removed hidden class on the #highestrated list');
        $('#guessImageContainer').append('<li><img src="' + highestRating.prev('img').attr('src') + '"><input id="guessMyValue" type="text"><button class="text-center" id="finishButton">Finish_Button</button><h2 class="text-center">Now Guess The Name Of The image</h2></li>');
    });
});
#confirm, #guessCheck {
    width: 110px;
    background-color: #990000;
    color: white;
    margin-left: 40px;
    border-radius: 20%
}

#finishButton {
    width: 110px;
    background-color: #990000;
    color: white;
    margin-left: 120px;
    margin-top: 33px border-radius : 20 %
}

#imagesConatiner {
    background-color: #f7f9f9;
}

#checkedImageContainer {
    background-color: #c0f9f9;
}

#guessImageContainer {
    background-color: #014747
}

.checkedImageList > img {
    width: 200px;
    height: 200px;
}

.hidden {
    display: none;
}

h1 {
    font-size: 22px;

}

#ageID {
    background-color: #0d7272;
    height: 200px;
}

img {
    width: 100px;
    height: 50px;
}

ul {
    list-style: none;
}

ul > li {
    padding-bottom: 7px;
}

#rulesList {
    font-size: 17px;
}

#gameRules {
    background-color: #af9607;
    color: white;
}

.rateInput {
    color: black;
}

#third-rule {
    color: black
}

.rateSelection {
    color: black;
}

#guessMyValue {
    color: black
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div class="container">
    <!--SECTION USER CONFIRMS THERE AGE TO VERIFY THE GAME BEING ABLE TO BE VISBLE TO THE USER -->
    <div id="ageID" class="text-center col-md-12">
        <h1>Let's make sure your good to play this Game , ENTER YOUR Birthyear :</h1>
        <input type="number" id="usersInput" min="1900" max="2018">
        <button id="birthYear" text="enterAge">enter_Age</button>
    </div>
    <!-- Section for users to read the rules of the game -->
    <div id="gameRules" class="hidden">
        <div class="text-center">
            <h1>Okay lets get started then here are the rules...</h1><br>
            <ol id="rulesList">
                <li style="color:black">Select your favorite images</li>
                <li><strong>YOU CAN ONLY SELECT THREE!!!</strong></li>
                <!--Don't display the third rule until the the user selects the favorite images -->
                <li style="padding-bottom:20px" class="hidden" id="third-rule">Now rate your favorite images.<strong>(DON'T
                    GIVE TWO IMAGES THE SAME RATING!!)</strong></li>
            </ol>
        </div>
        <div id="gameBoard" class=".col-md-12">
            <div id="imagesConatiner" class="col-md-4">
                <div class="text-center">
                    <ul id="imageNinpputList">
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=1" name="hammer"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=2" name="hardhat"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=3" name="paintbrush"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=4" name="screw"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=5" name="screwdriver"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=6" name="shovel"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=7" name="vest"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=8" name="wrench"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=9" name="cone"/>
                            <input type="checkbox" name="tool">
                        </li>
                        <li>
                            <image src="https://dummyimage.com/50x50/000/fff&text=10" name="falshlight"/>
                            <input type="checkbox" name="tool">
                        </li>
                    </ul>
                    <button id="confirm">100% Sure!!!</button>
                </div>
            </div>
            <!-- The checked images arent pushed into li's,
                            or taken off display hidden until three models are clicked and
                            confirm button is clicked-->
            <div id="checkedImageContainer" class="hidden col-md-4">
                <div class="text-center">
                    <h3 style="color:black"><strong>Now rate your favorite Images!!(#1-10)</strong></h3>
                    <ul class="checkedImageList">
                    </ul>
                    <button id="guessCheck">That's MY Opini0n</button>
                </div>
            </div>
            <!-- Now display the picture the user thought was the most attractive -and ask the user to guess her nationality-->
            <div id="guessImageContainer" class="hidden col-md-4 ">
                <ul id="guessImageList">
                </ul>
            </div>
        </div>
    </div>
</div>

【讨论】:

  • [![this is the output im getting][1]][1] [1]: i.stack.imgur.com/JMCuj.png 我还把代码改了一点...
  • jsfiddle.net/ko2qgr17 我将我的代码复制到了小提琴,我假设我的代码不起作用,因为我使用的是 boostrap css,尝试将我的代码从小提琴复制到你的代码编辑器,它应该可以工作
  • 谢谢,我才 7 个月开始编码,我的表弟是一名全栈开发人员,他尽可能多地教我,但他的时间有限,所以我很感激你投入的时间进来帮帮我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 2022-01-02
  • 1970-01-01
  • 2021-01-20
  • 1970-01-01
  • 2020-04-28
相关资源
最近更新 更多