在悬停/点击时获取DIV ID

时间:2018-06-02 10:14:55

标签: jquery html

我需要在点击或悬停时获取DIV的ID,以便在点击DIV转到URL时使用。

这就是我到目前为止......



$('.div1').mouseover(function() {
  var thisdiv = this.id;
});

$('.div1').click(function() {
  var divclick = document.getElementById(thisdiv);
  divclick.style.cursor = 'pointer';
  divclick.onclick = function() {
    window.location.href = "displayadvert.php?a=" + thisdiv;
  };
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1" id="1">ONE</div>
<div class="div1" id="2">TWO</div>
<div class="div1" id="3">THREE</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以在点击功能中使用this.id

$('.div1').click(function() {
 console.log(this.id);
 window.location.href = "displayadvert.php?a="+this.id;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1" id="1">ONE</div>
<div class="div1" id="2">TWO</div>
<div class="div1" id="3">THREE</div>

答案 1 :(得分:0)

这是解决方案 -

function goToSomeUrl(event) {
    console.log(event.target.id); 
}

$('.div1').mouseover(goToSomeUrl);
$('.div1').click(goToSomeUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1" id="1">ONE</div>
<div class="div1" id="2">TWO</div>
<div class="div1" id="3">THREE</div>