开发者

How to Populate jQuery Object with Data from Link Inside HTML List?

I have a list that looks like this:

<ul id="theLinks">
 <li><a href="one.php">One</a></li>
 &l开发者_运维技巧t;li><a href="two.php">Two</a></li>
 <li><a href="three.php">Three</a></li>
 <li><a href="four.php">Four</a></li>
</ul>

I would like to populate a jQuery Object with the data from that list so it looks like this:

var Links = {
  'One'   : 'one.php',
  'Two'   : 'two.php',
  'Three' : 'three.php',
  'Four'  : 'four.php' 
}

What is the best method for solving this problem?

Thanks in advance!


var Links = {};
$('#theLinks li a').each(function(){
    Links[this.innerHTML] = this.href.substring(this.href.lastIndexOf("/") + 1);
});

Fiddle link

Note: the links will not be in order because this is not an array.

Outputs:

Four: "four.php"
One: "one.php"
Three: "three.php"
Two: "two.php"


Not tested, but something like this:

var Links = {};
$('#theLinks li a').each(function(index, value) {         
    Links[value.text()] = value.attr('href');
});


var obj = {};
$("#theLinks a").map( function() {obj[$(this).text()] = this.href });
alert(obj.One);
alert(obj.Two);

Demo: http://jsfiddle.net/karim79/9SPUY/


Your result isn't an array, it's an object. (And it's nothing to do with jQuery, it's a straight JavaScript object. :-) )

Here's how you'd do that:

var Links = {};
$('#theLinks > li > a').each(function() {
    var $this = $(this);
    Links[$this.text()] = $this.attr('href');
});

Live example

Note I've used a fairly restrictive selector, #theLinks > li > a (an a only when it's the direct child of an li only when it's the direct child of #theLinks). You could use a looser one if your structure may vary slightly, such as #theLinks li a which allows for intermediate elements between both the ul and the lis and between the lis and the as. It depends entirely on what you want to achieve. But with the markup you gave, I'd probably be fairly tight about it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜