js判断奇偶数

JavaScript010

js判断奇偶数,第1张

<!DOCTYPE html>

<html lang="en">

<head>

<title>奇偶数</title>

</head>

<body>

<input type=text>

<input type=button value="判断" onclick="chk(value)">

<p id="demo"></p>

<script>

function chk(num) {

var inputs = document.getElementsByTagName('input')[0]

var value = inputs.value

num = value

console.log(num)

alert((num % 2 == 0) ? "偶数" : "奇数") //判断是否能整除2

}

</script>

</body>

</html>

js中有一个函数filter(),可以用来过滤数组中的特定元素;

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意: filter() 不会对空数组进行检测。

注意: filter() 不会改变原始数组。

语法 : filter((item, index, arr) =>{ ... })

filter中一共可已设置三个入参:其中item( 必填 )--代表数组中的每个元素,filter会对每个元素进行遍历;

index( 先填 )--每个元素的index;arr( 选填 )--指定要遍历的数组。

要筛选数组中的奇数位元素或者偶数位元素就可以用filte()方法。

例子:

1、遍历tr,得到鼠标所在tr的索引值,然后用二楼所说的方法判断奇偶;

2、用jQuery方便很多,在选择器后面加上":even"便选择的是索引值为偶数的元素,加":odd"便是索引值为奇数的元素。

下面是实现的代码,包括jQuery的:

<html>

<head>

<title></title>

<script type="text/javascript" src="jquery/jquery-1.4.2.js"></script>

<script type="text/javascript">

function changeStyle(elementId) {

var testTable = document.getElementById("testTable").children[0]

for(var i = 0i <testTable.children.lengthi++) {

if(testTable.children[i] == elementId) {

if(i % 2 == 1)//奇数

elementId.style.background = "red"

else//偶数

elementId.style.background = "blue"

}

}

}

//清除样式

function changeBack(elementId) {

elementId.style.background = ""

}

/**

* jQuery方法:

*/

$(document).ready(function() {

$("#jqueryTable tr:even").mouseover(function() {

$(this).css("background", "red")

})

$("#jqueryTable tr:odd").mouseover(function() {

$(this).css("background", "blue")

})

$("#jqueryTable tr").mouseout(function() {

$(this).css("background", "")

})

})

</script>

</head>

<body>

<table id="testTable" border="1">

<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">

<td>第</td><td>一行</td>

</tr>

<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">

<td>第</td><td>二行</td>

</tr>

<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">

<td>第</td><td>三行</td>

</tr>

<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">

<td>第</td><td>四行</td>

</tr>

<tr onmouseover="changeStyle(this)" onmouseout="changeBack(this)">

<td>第</td><td>五行</td>

</tr>

</table>

<table id="jqueryTable" border="1">

<tr>

<td>第一行</td>

</tr>

<tr>

<td>第二行</td>

</tr>

<tr>

<td>第三行</td>

</tr>

<tr>

<td>第四行</td>

</tr>

<tr>

<td>第五行</td>

</tr>

</table>

</body>

</html>