如何将对象中的数字与dom中的文本进行比较?

时间:2023-02-08 12:01:34

I have a function that picks a random number from 1 - 6 and then appends it to the DOM. I am trying to compare that number to numbers that are currently in a div in the DOM. So I stored those numbers in a var called cards. When I console.log() the var it returns an array. I converted that array to a string and then I retrieved the text. What is the best way to go about comparing the numbers? Should I do a for loop and if any of those numbers match one of the random numbers drawn take some action? Can some one show me an example of doing this? My code is below.

我有一个函数,从1 - 6中选择一个随机数,然后将其附加到DOM。我试图将该数字与当前在DOM中的div中的数字进行比较。所以我将这些数字存储在名为card的var中。当我在console.log()时,var返回一个数组。我将该数组转换为字符串,然后检索文本。比较这些数字的最佳方法是什么?我是否应该进行for循环,如果这些数字中的任何一个与绘制的随机数匹配,请采取一些措施?有人能告诉我这样做的一个例子吗?我的代码如下。

 $(function(){
   function dice1(){
       var randomNumber =  Math.floor(Math.random() * 6) + 1;
       $('#instructions').text(randomNumber);
       return randomNumber;
   }
    function dice2(){
        var randomNumber =  Math.floor(Math.random() * 6) + 1;
        $('#instructions2').text(randomNumber);
        return randomNumber;

    }
    $('#dice1').click(function() {
        dice1();
        var cards = $('#cards div');
        var single = cards.toString();

        console.log(cards.text());
        if ($('#instructions').text() == cards.text()) {
            console.log('match');
        }

    });

    $('#dice2').click(function(){
        dice2();
    });


 });
  <section id="container">
    <div id="cards">
        <div id="1">1</div>
        <div id="2">2</div>
        <div id="3">3</div>
        <div id="4">4</div>
        <div id="5">5</div>
        <div id="6">6</div>
        <div id="7">7</div>
        <div id="8">8</div>
        <div id="9">9</div>
    </div>

    <section>
        <button id="dice1">Roll dice1</button>
        <button id="dice2">Roll dice2</button>
        <div id="instructions"></div>
        <div id="instructions2"></div>
    </section>

</section>

4 个解决方案

#1


Why not store the cards directly in an array like this:

为什么不直接将卡存储在这样的数组中:

var cards = [1,2,3,4,5,6,7,8,9];

Then do the comparison like this:

然后做这样的比较:

var number = parseInt($("#instructions").text());

if(cards.indexOf(number) >= 0)
    console.log("Number found");
else
    console.log("Number not found");

If you really want to do it your way, you can do this:

如果你真的想按自己的方式去做,你可以这样做:

$(".cards div").each(function(){
    var number = parseInt($("#instructions").text());
    var card = parseInt($(this).text());
    if(card == number)
            console.log("Number found");

});

#2


Well you could indeed do it with a for loop:

那么你确实可以用for循环来做到这一点:

$('#dice1').click(function() {
    var random_number = dice1();
    var cards = $('#cards div');

    for(var i = 0; i < cards.length; i++ ) {
       if($(this).html() == random_number) {
           alert('Do something!');
       }
    }

    console.log(cards.text());
    if ($('#instructions').text() == cards.text()) {
        console.log('match');
    }

});

But you could also directly match to the ID you've set:

但您也可以直接匹配您设置的ID:

$('#dice1').click(function() {
    var random_number = dice1();
    var card = $('#cards div[id='+random_number+']');
    if(card.length > 0) {
        alert('Do something!');
    }
});

Remember though, that the ID attribute can not start with a number, so I would create my own attribute here:

但请记住,ID属性不能以数字开头,所以我会在这里创建自己的属性:

<div id="cards">
    <div data-number="1">1</div>
    <div data-number="2">2</div>
    <div data-number="3">3</div>
    <div data-number="4">4</div>
    <div data-number="5">5</div>
    <div data-number="6">6</div>
    <div data-number="7">7</div>
    <div data-number="8">8</div>
    <div data-number="9">9</div>
</div>

And then use jQuery like so:

然后像这样使用jQuery:

$('#dice1').click(function() {
    var random_number = dice1();
    var card = $('#cards div[data-number='+random_number+']');
    if(card.length > 0) {
        alert('Do something!');
    }
});

#3


You can do something like this:

你可以这样做:

New JS:

 $(function () {
     function dice1() {
         var randomNumber = Math.floor(Math.random() * 6) + 1;
         $('#instructions').text(randomNumber);
         return randomNumber;
     }

     function dice2() {
         var randomNumber = Math.floor(Math.random() * 6) + 1;
         $('#instructions2').text(randomNumber);
         return randomNumber;

     }
     $('#dice1').click(function () {
         var num1 = dice1();

         $('#cards div').each(function (index,item) {
             if ($(item).text() == num1) {
                 $(item).css("color", "red");
             }
         });


         $('#dice2').click(function () {
             dice2();
         });


     });
 });

Fiddle example

#4


I just learned a way of doing it that solves it dynamically and personally I think it's easier to follow.

我刚刚学会了一种方法,可以动态地解决这个问题。我认为这样做更容易理解。

 <div data-hook="cards" id="cards">
        <div data-value="1" id="1">1</div>
        <div data-value="2" id="2">2</div>
        <div data-value="3" id="3">3</div>
        <div data-value="4" id="4">4</div>
        <div data-value="5" id="5">5</div>
        <div data-value="6" id="6">6</div>
        <div data-value="7" id="7">7</div>
        <div data-value="8" id="8">8</div>
        <div data-value="9" id="9">9</div>
    </div>

 $(function(){
   function dice1(){
       var randomNumber =  Math.floor(Math.random() * 6) + 1;
       $('#instructions').text(randomNumber);
       return randomNumber;
   }

    $('#dice1').click(function() {
        dice1();

        $('[data-hook=cards] [data-value]').find('#instructions'); //'data-hook=cards] [data-value]' selects the element by attr'
        var rolledNum = $('#instructions').text(),
                selector = '[data-value=' + rolledNum + ']',
                $card = $('[data-hook=cards]').find(selector);
        //Instead of using an $.each or for loop to compare two numbers I am taking the random number and finding it on the div and then modifying the div.
        console.log($card);
        $card.css({'opacity':.2});

    });        
 });

#1


Why not store the cards directly in an array like this:

为什么不直接将卡存储在这样的数组中:

var cards = [1,2,3,4,5,6,7,8,9];

Then do the comparison like this:

然后做这样的比较:

var number = parseInt($("#instructions").text());

if(cards.indexOf(number) >= 0)
    console.log("Number found");
else
    console.log("Number not found");

If you really want to do it your way, you can do this:

如果你真的想按自己的方式去做,你可以这样做:

$(".cards div").each(function(){
    var number = parseInt($("#instructions").text());
    var card = parseInt($(this).text());
    if(card == number)
            console.log("Number found");

});

#2


Well you could indeed do it with a for loop:

那么你确实可以用for循环来做到这一点:

$('#dice1').click(function() {
    var random_number = dice1();
    var cards = $('#cards div');

    for(var i = 0; i < cards.length; i++ ) {
       if($(this).html() == random_number) {
           alert('Do something!');
       }
    }

    console.log(cards.text());
    if ($('#instructions').text() == cards.text()) {
        console.log('match');
    }

});

But you could also directly match to the ID you've set:

但您也可以直接匹配您设置的ID:

$('#dice1').click(function() {
    var random_number = dice1();
    var card = $('#cards div[id='+random_number+']');
    if(card.length > 0) {
        alert('Do something!');
    }
});

Remember though, that the ID attribute can not start with a number, so I would create my own attribute here:

但请记住,ID属性不能以数字开头,所以我会在这里创建自己的属性:

<div id="cards">
    <div data-number="1">1</div>
    <div data-number="2">2</div>
    <div data-number="3">3</div>
    <div data-number="4">4</div>
    <div data-number="5">5</div>
    <div data-number="6">6</div>
    <div data-number="7">7</div>
    <div data-number="8">8</div>
    <div data-number="9">9</div>
</div>

And then use jQuery like so:

然后像这样使用jQuery:

$('#dice1').click(function() {
    var random_number = dice1();
    var card = $('#cards div[data-number='+random_number+']');
    if(card.length > 0) {
        alert('Do something!');
    }
});

#3


You can do something like this:

你可以这样做:

New JS:

 $(function () {
     function dice1() {
         var randomNumber = Math.floor(Math.random() * 6) + 1;
         $('#instructions').text(randomNumber);
         return randomNumber;
     }

     function dice2() {
         var randomNumber = Math.floor(Math.random() * 6) + 1;
         $('#instructions2').text(randomNumber);
         return randomNumber;

     }
     $('#dice1').click(function () {
         var num1 = dice1();

         $('#cards div').each(function (index,item) {
             if ($(item).text() == num1) {
                 $(item).css("color", "red");
             }
         });


         $('#dice2').click(function () {
             dice2();
         });


     });
 });

Fiddle example

#4


I just learned a way of doing it that solves it dynamically and personally I think it's easier to follow.

我刚刚学会了一种方法,可以动态地解决这个问题。我认为这样做更容易理解。

 <div data-hook="cards" id="cards">
        <div data-value="1" id="1">1</div>
        <div data-value="2" id="2">2</div>
        <div data-value="3" id="3">3</div>
        <div data-value="4" id="4">4</div>
        <div data-value="5" id="5">5</div>
        <div data-value="6" id="6">6</div>
        <div data-value="7" id="7">7</div>
        <div data-value="8" id="8">8</div>
        <div data-value="9" id="9">9</div>
    </div>

 $(function(){
   function dice1(){
       var randomNumber =  Math.floor(Math.random() * 6) + 1;
       $('#instructions').text(randomNumber);
       return randomNumber;
   }

    $('#dice1').click(function() {
        dice1();

        $('[data-hook=cards] [data-value]').find('#instructions'); //'data-hook=cards] [data-value]' selects the element by attr'
        var rolledNum = $('#instructions').text(),
                selector = '[data-value=' + rolledNum + ']',
                $card = $('[data-hook=cards]').find(selector);
        //Instead of using an $.each or for loop to compare two numbers I am taking the random number and finding it on the div and then modifying the div.
        console.log($card);
        $card.css({'opacity':.2});

    });        
 });