如果特定div中有点击,我想提醒。
情景:
<div class="container">
<div class="header"> <h1>Headline<h1> </div>
<div class="productbox"></div>
</div>
我知道如何提醒标题......
$("h1:contains('Headline')").one( function() {
alert("ALERT Headline");
});
...以及如何提醒Productbox
$(".productBox").click(function){
alert("ALERT Productbox click");
});
现在我想&#34;结婚&#34;这两个。
我的代码:
if (!$("h1:contains('Headline')").one(function) && !$(".productBox").click(function)){
alert:("Alert when h1 contains Headline and ProductBox is clicked")};
取自:Jquery "if this and if that" then do this
旁注:没有独特的选择器(我可以使用的元素或ID),这就是我想要使用标题的原因。
虽然&#34;标题&#34;不直接位于类productBox
之上答案 0 :(得分:2)
您的活动应仅在ProductBox上,并且您需要检查prev元素的状态。
$(".productBox").click(function(){
if ( $(this).prev().find("h1:contains('Headline')").size() > 0 )
{
alert("Alert when h1 contains Headline and ProductBox is clicked");
}
});
答案 1 :(得分:1)
你应该知道click
是一个事件,其中的功能只有在有人实际点击时才会被调用。当代码正确启动时,其余代码将被执行,请记住这一点。
您的代码包含以下语义部分:
Headline
的H1是否存在您的代码:
//Registering an on click handler, code inside here fires whe someone clicks
$(".productBox").click(function(){
//check if headline exists in your code (i prefer checking with length, since it returns a jquery array of found elements for this selector)
if ( $("h1:contains('Headline')").length == 1 )
{
//alert user if so
alert("Alert when h1 contains Headline and ProductBox is clicked");
}
});
一个与click相同的功能:但只有处理程序会触发一次。你可以像这样使用它:
//Registering a click handler that only fires once, code inside here fires whe someone clicks
$(".productBox").one("click",function(){
//check if headline exists in your code (i prefer checking with length, since it returns a jquery array of found elements for this selector)
if ( $("h1:contains('Headline')").length == 1 )
{
//alert user if so
alert("Alert when h1 contains Headline and ProductBox is clicked");
}
});