如果有'It’点击一个特定的分区

Alert if there's a click in a specific div

本文关键字:一个 分区 It 如果      更新时间:2023-09-26

如果在特定的分区中有点击,我想提醒。

场景:

<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");
});

现在我想"嫁给"这两个。

我的代码:

if (!$("h1:contains('Headline')").one(function) && !$(".productBox").click(function)){
alert:("Alert when h1 contains Headline and ProductBox is clicked")};

取自:Jquery";如果这个和如果那个";然后做这个

旁注:没有唯一的选择器(我可以使用的元素或ID),这就是我想使用Headline的原因。

尽管"headline"并不直接位于productBox类之上

您的事件应该只在ProductBox上,并且在其中您需要检查prev元素的条件。

$(".productBox").click(function(){ 
 if ( $(this).prev().find("h1:contains('Headline')").size() > 0 )
 {
   alert("Alert when h1 contains Headline and ProductBox is clicked");
 }
});

您应该知道click是一个事件,只有当有人实际单击时才会调用其中的函数。代码的其余部分将在代码正确启动时执行,请记住这一点。

您的代码包含以下语义部分:

  • 分配一个点击处理程序:当有人点击时,这个函数就会被激发
  • 检查是否存在具有内容Headline的H1
  • 如果是,则发出警报
  • 点2和3应该只在有人点击时触发(所以当点击处理程序被触发时)

您的代码:

//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");
  }
});

关于jQuery one()

http://api.jquery.com/one/

其中一个函数与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");
  }
});