简体   繁体   English

如果h1和p等于变量jquery,则单击链接

[英]Click link if h1 and p is equal to variable jquery

If i have something like this: 如果我有这样的事情:

 <div class="inner-article"> <h1><a class="name-link" href="link">Exempel 1</a></h1> <p><a class="name-link" href="link">a</a></p> </div> <div class="inner-article"> <h1><a class="name-link" href="link">Exempel 2</a></h1> <p><a class="name-link" href="link">a</a></p> </div> <div class="inner-article"> <h1><a class="name-link" href="link">Exempel 2</a></h1> <p><a class="name-link" href="link">b</a></p> </div> <div class="inner-article"> <h1><a class="name-link" href="link">Exempel 3</a></h1> <p><a class="name-link" href="link">a</a></p> </div> 

And i wanted to click the link if h1 = var1 and p = var2 我想单击链接,如果h1 = var1和p = var2
I have this code: 我有以下代码:

 var var1 = "Exempel 2"; var var2 = "a"; $( "h1 > a" ).each(function( index ) { if($( this ).text() == var1){ $( this )[0].click(); } }); 
The code works fine but the problem is, when there are more h1 with the same text, it opens both links and end up on the last link. 该代码可以正常工作,但问题是,当有更多具有相同文本的h1时,它将打开两个链接并最终到达最后一个链接。 So how do i open the right link? 那么,我该如何打开正确的链接?

You need to check if the text from both the h1 and the adiacent p match your criteria. 您需要检查是否同时来自h1和adiacent p的文本符合您的条件。

var var1 = "Exempel 2";
var var2 = "a";

    $( "h1 > a" ).each(function( index ) {
             if($( this ).text() == var1 && 
                   $( this ).closest('div').find("p > a").text() == var2) {
                $( this )[0].click();
            }
        });

this should work.It serves less loops 这应该工作。它减少循环

 var var1 = "Exempel 2"; 
var var2 = "a"; 

$( "div" ).each(function( index ) {         
    if($( this ).find('a:first').text() == var1 && $( this ).find('a:last').text()  == var2)
       $( this ).find('a:first').click()
       return false;
     }  
});

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

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