开发者

Click sub-links in a div?

开发者 https://www.devze.com 2023-02-17 20:39 出处:网络
I want to click 4 different links within a div that have no ID. Let\'s say the div\'s name is \"links\".

I want to click 4 different links within a div that have no ID. Let's say the div's name is "links".

So I want it to click link #1 of 5 inside of this div.

I would prefer to开发者_如何学C use location.href.

How can this be done?


You can use some jQuery to trigger a click event on the first a element inside a div, given that the div's ID is links as you said:

$('div#links a:first').click();


  • DEMO: http://jsbin.com/ucedu5
//loop and assing onclick event to all <a> inside <div>
var div_a = document.getElementById('links').getElementsByTagName('a');     
  for (var i=0;i<div_a.length;i++) {
    div_a[i].onclick = function() {
    alert( this.href );
    };
  }

//loop and assing onclick event only to #1 <a> inside <div>
var div_a = document.getElementById('links').getElementsByTagName('a');   
  for (var i=0;i<div_a.length;i++) {
    if ( i === 0 ) {
    div_a[i].onclick = function() {
    alert( this.href );
    };
   }
  }

   //directly assing onclick event to the #1 <a> inside <div>
   document.getElementById('links').getElementsByTagName('a')[0].onclick = function(){
   alert( this.href );
   };
0

精彩评论

暂无评论...
验证码 换一张
取 消