将jquery函数绑定到元素 [英] Bind a jquery function to elements

查看:125
本文介绍了将jquery函数绑定到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jquery非常陌生,需要一些帮助.输入文本框时,我试图更改css元素.我在文本框中应用了一个CSS类,并且在文本框周围有几个div标签.

当用户选择文本框时,我想更改所需的div标签.

这是html的外观

<div class="left">
    <div class="right">
        <input name="myTextBoxID" type="text" id="myTextBoxID" class="myTextBox" />
        <span id="rfInput"></span>
    </div>
</div>

我的jquery看起来像这样

<script language="javascript" type="text/javascript">
   $(function () {
       $('.myTextBox').focus(function () {

           $('.box.left').addClass("active");
       }).blur(function () {
           $('.box.left').removeClass("active");
       });
   });
</script>

现在,jQuery正在工作,并改变了焦点并模糊了类,但是它会影响class ="myTextBox"的所有元素,但我如何才能将jquery附加到所有元素,但是只能将CSS更改触发到元素外部的选定文本框上课?

任何帮助都会很棒!

解决方案

<script language="javascript" type="text/javascript">
   $(function () {
       $('.myTextBox').focus(function () {
           $(this).closest('.left').addClass("active");
       })
       .blur(function () {
           $(this).closest('.left').removeClass("active");
       });
   });


</script>

this是指接收事件的元素.

因此,您将this包装到jQuery对象$(this)中,并使用指定的类访问closest()祖先.

.closest()- http://api.jquery.com/closest/

I am very new to jquery and need some help. I am trying to change a css element when I enter a textbox. I have applied a css class to my textboxes and I have a couple of div tags around my textboxes.

When a user selects the textbox I want to change the desired div tag.

This is how the html looks

<div class="left">
    <div class="right">
        <input name="myTextBoxID" type="text" id="myTextBoxID" class="myTextBox" />
        <span id="rfInput"></span>
    </div>
</div>

my jquery looks like this

<script language="javascript" type="text/javascript">
   $(function () {
       $('.myTextBox').focus(function () {

           $('.box.left').addClass("active");
       }).blur(function () {
           $('.box.left').removeClass("active");
       });
   });
</script>

Now the jquery is working and changes the class on focus and blur however it effects all elements witht he class="myTextBox" how can I get jquery to attach to all elements however only fire the css change to the selected textboxes outside elements class?

Any help would be great!

解决方案

<script language="javascript" type="text/javascript">
   $(function () {
       $('.myTextBox').focus(function () {
           $(this).closest('.left').addClass("active");
       })
       .blur(function () {
           $(this).closest('.left').removeClass("active");
       });
   });


</script>

this refers to the element that received the event.

So you wrap this into a jQuery object, $(this) and access the closest() ancestor with the class you designate.

.closest() - http://api.jquery.com/closest/

这篇关于将jquery函数绑定到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆