如何删除获取id的一部分

时间:2016-08-05 09:53:04

标签: javascript jquery

嗨我有一个div有id newvalue1,newvalue2,........当我点击任何一个



<div id="newvalue1"></div>
<div id="newvalue2"></div>
<div id="newvalue3"></div>
<div id="newvalue4"></div>
&#13;
&#13;
&#13;

div我希望得到id的一部分,例如,如果我点击div newvalue1 i

如果我点击newvalue2,我想在变量

中输入2

2 个答案:

答案 0 :(得分:1)

试试这个,这个例子告诉你如何做到这一点。

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
.square{
	width: 100px;
	height: 100px;
	border: 2px solid black;
	margin: 10px;
	color: white;
	text-align: center;
	font-size: 20px;
	cursor: pointer;
}
</style>


<body>

<div id="newvalue1" class="square" style="background-color:orange">one</div>
<div id="newvalue2" class="square" style="background-color:red">two</div>
<div id="newvalue3" class="square" style="background-color:pink">three</div>
<div id="newvalue4" class="square" style="background-color:purple">four</div>
<div id="newvalue5" class="square" style="background-color:blue">five</div>


<script type="text/javascript">
	$(".square").click(function(){
		var theid = $(this).attr('id');
		var integerval = theid.replace( /[^\d.]/g,'');
		alert(theid);
		alert(integerval);

		//inteterval will give you the nlumber.
	});
</script>


</body>
</html>
&#13;
&#13;
&#13;

希望这会对你有所帮助。

答案 1 :(得分:0)

试试这个

&#13;
&#13;
function test(t){
var v = t.id.split('newvalue');
console.log(v[1]);
}
&#13;
<div id="newvalue1" onclick="test(this)">1</div>
<div id="newvalue2" onclick="test(this)">2</div>
<div id="newvalue3" onclick="test(this)">3</div>
<div id="newvalue4" onclick="test(this)">4</div>
&#13;
&#13;
&#13;