简体   繁体   English

找到最接近的类onclick

[英]Find closest class onclick

I have the following HTML: 我有以下HTML:

<div class="col-md-10">
   <input type="text" name="postcode" class="postcodeinput" /> 
</div>

<div class="col-md-2">
    <a class="picklocation"><i class="fa fa-search" aria-hidden="true"></i>   
    </a>
</div>

When you click on "pickuplocation" I need to get the value of "postcodeinput". 当您单击“ pickuplocation”时,我需要获取“ postcodeinput”的值。

The issue is that there are multiple postcode loop ups on the page so I can't just use $('.postcodeinput').val() as there are two and both are handled in the same function. 问题是页面上有多个邮政编码循环,所以我不能只使用$('.postcodeinput').val()因为有两个并且都在同一个函数中处理。

What I want to do is find the closest element .postcodeinput and get the value. 我想做的是找到最接近的元素.postcodeinput并获取值。 I have tried the following jQuery: 我尝试了以下jQuery:

$('.picklocation').click(function() {
    var postcode = null;
    console.log($(this).prev('.postcodeinput').val());
});

I have tried this, however, I am just getting 'undefined' 我已经尝试过了,但是,我只是变得“未定义”

You need to traverse to postcodeinput is child of the sibling element of picklocation 's parent element. 您需要遍历到postcodeinputpicklocation的父元素的同级元素的子元素。

$('.picklocation').click(function() {
    console.log($(this).parent().prev().find('.postcodeinput').val());
});

i made another solution. 我提出了另一个解决方案。 now ,after i made the snippet, i realized that it looks like the one Satpal gave ( you can use that one ) . 现在,在我制作了代码段之后,我意识到它看起来就像Satpal给出的代码一样(您可以使用该代码)。 you should use my solution in case your HTML changes and you want to be more specific about where to look for the value. 您应该使用我的解决方案,以防HTML发生更改,并且希望更具体地了解在哪里寻找价值。

first look for the parent ( that is a div ) of the button, then search the previous element ( div ) that has a child .postcodeinput . 首先查找按钮的父级(即div),然后搜索具有子级.postcodeinput的上一个元素(div)。

second in that div search for the .postcodeinput and get it's value 在该div中搜索第二个 .postcodeinput并获取其值

third only if that value in not null...do something with it ( in this case write in console ) 仅当该值不为null时...才执行第三次操作(在这种情况下,请在控制台中编写)

 $('.picklocation').click(function() { var postcode = $(this).parent("div").prev("div").has(".postcodeinput") var postcodeVal = $(postcode).find('.postcodeinput').val(); if( postcodeVal != 0) { console.log(postcodeVal); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="col-md-10"> <input type="text" name="postcode" class="postcodeinput" /> </div> <div class="col-md-2"> <a class="picklocation"><i class="fa fa-search" aria-hidden="true">First Button</i> </a> </div> <div class="col-md-10"> <input type="text" name="postcode" class="postcodeinput" /> </div> <div class="col-md-2"> <a class="picklocation"><i class="fa fa-search" aria-hidden="true">Second Button</i> </a> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM