HTML:
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;"></div>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;"></div>
JQuery:
<script type="text/javascript">
$(document).ready(function() {
// Add onclick handler to checkbox w/id checkme
$('.showimage').click(function() {
var id = $(this).attr('id');
var ret = id.split("_");
var str1 = ret[1];
//alert(str1);
var id = $(this).attr('id');
var ret = id.split("_");
var str2 = ret[1];
//alert(str2);
//$(".icon_"+id).show();
// $("#icon").show();
if (str1 == str2) {
alert(str1);
$(".icon_" + str1).show();
//exit;
//alert("hi")
} else {
alert("sec");
$(".icon_" + str1).hide();
}
});
});
</script>
为什么不隐藏else部分
最佳答案
你的问题:为什么不隐藏 else 部分?
这是因为 $(this)
它指的是当前元素,该元素已获得事件引发的选择器的上下文。所以,
var id = $(this).attr('id');
上面的变量被使用了两次,都指向同一个对象。所以在 if 条件下:
if (str1 == str2) {
两个值总是相同的,因此 else
永远不会被执行。
最好将 .focus()/.blur()
事件与 .toggle(condition)
一起使用:
$(function(){
$('.showimage').on('focus blur', function(e){
$(this).next('div').toggle(e.type === "focus")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;">one</div><br>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;">two</div>
关于javascript - 如何根据此编码显示隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34283174/