开发者

Click sub-links in a div?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜