我有以下代码。如何在这里使用'或'运算符来缩短我的代码?
$(document).ready(function() {
$("#id_event_type_1").click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
});
$(document).ready(function(){
$("#id_event_type_2").click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
});
$(document).ready(function() {
$("#id_event_type_3").click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
});
答案 0 :(得分:1)
因为他们似乎也这样做:
$(document).ready(function() {
$("#id_event_type_1,#id_event_type_2,#id_event_type_3").click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
});
答案 1 :(得分:1)
这个怎么样?
$(function() {
for (var x = 1; x <= 3; x++) {
$("#id_event_type_" + x).click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
}
});
我不知道您的标记是什么样的,但是更改循环结束编号比继续添加到该字符串更容易(在更多条目之后很难查看)。
答案 2 :(得分:1)
您可以使用jQuery 以 ^=
选择器开头。
$(document).ready(function() {
$("[id^=id_event_type]").click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
}); //END $(document).ready()
以选择开头,其工作方式如下:$([attribute ^= string])
,允许您使用id
或class
或name
或{指定所有元素{1}} 以指定的字符串开头。
使用以开头时,您还可以拆分点击的元素的特定属性字符串,如下所示:
??
最后一点。您不需要将每个例程包含在其自己的(document).ready()函数中。你只需要一个,然后每个例程可以一个接一个地列在其中。
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
div {height:100px; width:100px; margin:20px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("[id^=id_event_type]").click(function(){
var myid = $(this).attr('id');
var num = myid.split('_')[3];
alert('You clicked on: ' +myid+ ', which is number ' +num);
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
}); //END $(document).ready()
</script>
</head>
<body>
<div id="id_event_type_1" style="background-color:red"></div>
<div id="id_event_type_2" style="background-color:blue"></div>
<div id="id_event_type_3" style="background-color:green"></div>
</body>
</html>
答案 3 :(得分:0)
$(document).ready(function() {
$("#id_event_type_1, #id_event_type_2, #id_event_type_3").click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
});
答案 4 :(得分:0)
$(function() {
$('[id^=id_event_type_]').click(function(){
$("#id_end_date").show();
$('label[for="id_end_date"]').show();
});
});
答案 5 :(得分:0)
您只需要1个document.ready事件,无需重复。 另外,我会考虑为这些项目提供一个类,并且只需为您的点击事件使用类选择器。
$(document).ready(function () {
$(".eventType").click(function(){
/* do whatever */
});
});