繁体   English   中英

如何在javascript和jquery中接收带有输入的数字并只返回偶数?

[英]how to receive numbers with input and return only even numbers in javascript & jquery?

如何在javascript和jquery中接收带有输入的数字并只返回偶数?

$(document).ready(function() {
    $("#submit").click(function() {
        var nums = $("#nums").val();
        var numsf = nums.split(',');
        var res = numsf.join(", ");
        var even = 
        $("p").append(even + "<br>");
    });
});

使用模数 2 检测是否为偶数

$(document).ready(function () {
    $("#submit").click(function () {
        var nums = parseInt($("#nums").val());
        var isEven = nums % 2 == 0;
        if(isEven){
            $("p").append(nums);
        }
    });
});

更新

$(document).ready(function() {
  $("#submit").click(function() {
    var nums = $("#nums").val();
    var numsf = nums.split(',');
    var evens = [];
    for (var i = 0; i < numsf.length; i++) {
      if (parseInt(numsf[i]) % 2 == 0) {
        evens.push(numsf[i]);
      }
    }
    var res = evens.join(", ");
    $("p").append(res + "<br>");
  });
});

这解决了您的问题。 我提供了演示链接。

演示

$("document").ready(function() {
    $("#submit").click(function() {
        var nums = $("#nums").val();
        var numsf = nums.split(','); //array of comma separated values
        var evens = [];
        //loops through the array. see documentation for jQuery.each()
        $.each(numsf,function(i, _this){
            if (!isNaN(_this) && parseInt(_this) % 2 == 0)
                evens.push(_this);
        });
        var res = evens.toString();
        $("p").append(res + "<br>");
    });
});

jQuery.each()

尝试这个

 $(document).ready(function() { var numsf = [1, 2, 3, 4, 5, 6, 7, 8, 9]; $.each(numsf, function(a, b) { if (b % 2 == 0) { alert(b); return b; } }) })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我个人建议如下——假设id="nums"的元素采用逗号分隔的数字字符串:

// binding an anonymous function tot he click event
// of the element with 'id="submit"', passing the
// event ('e') into the function:
$("#submit").click(function (e) {

    // preventing any default behaviour of the
    // element's click event:
    e.preventDefault();

    // updating the text of the <p> element(s)
    // (it would be better, in practice, to use
    // a more specific selector):
    $('p').text(function () {

        // splitting the value of the '#nums' element on the
        // comma (',') character to form an array; using
        // Array.prototype.filter() to filter that array:
        return $('#nums').val().split(',').filter(function (n){
            // the first argument to the anonymous function
            // (here 'n') is the array element of the array
            // over which we're iterating.

            // we trim the number-string (removing leading
            // and trailing spaces), and then use parseInt()
            // to convert that to a number in base 10 (the
            // second, the radix, argument to parseInt());
            // if the remainder of the division of that number
            // by two is 0 then the number is even and
            // the assessment evaluates to true, so we
            // keep that number (discarding those numbers
            // for which the assessment evaluates to false):
            return parseInt(n.trim(), 10) % 2 === 0;

        // joining the filtered-array back together:
        }).join(', ');
    });
});

 $("#submit").click(function(e) { e.preventDefault(); $('p').text(function() { return $('#nums').val().split(',').filter(function(n) { return parseInt(n.trim(), 10) % 2 === 0; }).join(', '); }); });
 p::before { content: 'Even numbers: '; display: block; color: #999; } p:empty::before { content: ''; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action=""> <fieldset> <label>Enter comma-separated numbers: <input id="nums" type="text" placeholder="1,2,3,4..." /> </label> </fieldset> <fieldset> <button id="submit" type="button">Submit</button> </fieldset> </form> <p></p>

外部JS Fiddle 演示,用于实验/开发等。

顺便说一句,这可以在纯 JavaScript 中类似地完成 - 无需使用库,例如​​ jQuery - 使用以下内容:

// getting the element with 'id="submit"' and binding an
// anonymous function as the click event-handler, passing
// the event ('e') into the function:
document.getElementById('submit').addEventListener('click', function (e) {

    // preventing any default actions the element might have:
    e.preventDefault();

    // retrieving the <form> associated with the clicked element,
    // then getting the next element sibling, and setting its
    // text-content:
    this.form.nextElementSibling.textContent = document

    // getting the element with the id of 'nums':
    .getElementById('nums')

    // retrieving its value, splitting that value on comma
    // characters to form an array:
    .value.split(',')

    // filtering that array, using Array.prototype.filter():
    .filter(function (n) {
        // exactly the same as above:
        return parseInt(n.trim(), 10) % 2 === 0;
    }).join(', ');
});

 document.getElementById('submit').addEventListener('click', function(e) { e.preventDefault(); this.form.nextElementSibling.textContent = document .getElementById('nums') .value.split(',').filter(function(n) { return parseInt(n.trim(), 10) % 2 === 0; }).join(', '); });
 p::before { content: 'Even numbers: '; display: block; color: #999; } p:empty::before { content: ''; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action=""> <fieldset> <label>Enter comma-separated numbers: <input id="nums" type="text" placeholder="1,2,3,4..." /> </label> </fieldset> <fieldset> <button id="submit" type="button">Submit</button> </fieldset> </form> <p></p>

外部JS Fiddle 演示,用于实验/开发等。

参考:

暂无
暂无

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

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