2014-12-05 53 views
0

我有一个input,应该添加一个clicked类的另一个元素的ID为#zip点击。下面是代码:如何添加一个类到一个元素,当我点击与jquery不同的元素

$('#billing_zip').click(function() { 
 
    $('#zip').addClass('clicked'); 
 
});
#zip { 
 
    color: #444; 
 
    font-style: italic; 
 
    position: absolute; 
 
    top: 8px; 
 
    left: 35px 
 
} 
 
.clicked { 
 
    display: none; 
 
}
<div class="chkField"> 
 
     <label for="billing_zip">Zip</label> 
 
     <input type="text" onchange="clearContent(this);check_address('billing');" class="txtBoxStyle hasPlaceholder" tabindex="10" size="10" value="" id="billing_zip" maxlength="15" name="billing_zip"> 
 
     <!--START: req_billing_zip--> 
 
     <img width="12" height="12" alt="" src="assets/templates/common/images/error2.gif"> 
 
     <!--END: req_billing_zip--> 
 
     <div class="clear"></div> 
 
     <div id="zip">zip</div> 
 
     </div>

我不知道为什么上面的jQuery不工作。

+0

至于我可以看到你的代码工作得精细。 “点击”类正在得到应用。 http://jsfiddle.net/8L5qdeu7/ – 2014-12-05 04:30:46

+0

不要忘记把你的jQuery代码包装在'$(document).ready(function(){//你的jquery代码//});' – 2014-12-05 04:31:27

+0

add id ='billing_zip '在标签。您将billing_zip声明为自定义属性(for)。但是你选择它作为id。 – zanhtet 2014-12-05 04:32:19

回答

0

退房这里jsfiddle。如果需要使用document.ready。我发现的一个重点是,如果输入框上的占位符文本很长,则它覆盖了整个输入框区域,并且不允许触发点击事件。请参阅jsfiddle。

$('#billing_zip').click(function() { 
    $('#zip').addClass('clicked'); 
}); 

$('#zip').click(function() { 
    $('#zip').addClass('clicked'); 
}); 
0

您的代码工作正常

这可能是2可能出现的问题:

  1. 你缺少添加jQuery的参考:

  2. 你应该换你的代码里面的document.ready事件:

    $(function(){ $('#billing_zip')。click(function(){ $('#zip')。addClass('clicked'); }); });

2

你忘了声明billing_zip的id。

$(document).ready(function(){ 
 
$('#billing_zip').click(function() { 
 
    alert('hi'); 
 
    $('#zip').addClass('clicked'); 
 
}); 
 
});
#zip { 
 
    color: #444; 
 
    font-style: italic; 
 
    position: absolute; 
 
    top: 8px; 
 
    left: 35px 
 
} 
 
.clicked { 
 
    display: none; 
 
}
<div class="chkField"> 
 
     <label id="billing_zip" for="billing_zip">Zip</label> 
 
     <input type="text" onchange="clearContent(this);check_address('billing');" class="txtBoxStyle hasPlaceholder" tabindex="10" size="10" value="" id="billing_zip" maxlength="15" name="billing_zip"> 
 
     <!--START: req_billing_zip--> 
 
     <img width="12" height="12" alt="" src="assets/templates/common/images/error2.gif"> 
 
     <!--END: req_billing_zip--> 
 
     <div class="clear"></div> 
 
     <div id="zip">zip</div> 
 
     </div>

0

如果这只是你想要的。然后你就可以直接做,如:

$('#billing_zip').click(function() { 
    $('#zip').css("display","none"); // or you can use hide or fadeout property. 
}); 
0

当我包你的jQuery代码在“$(文件)。就绪”它的工作:

$(document).ready(function(){ 
    $('#billing_zip').click(function() { 
    $('#zip').addClass('clicked'); 
}); 
}); 
相关问题