用于在客户端上操作IU的jQuery

时间:2012-01-27 21:04:59

标签: jquery html-lists

我开始学习jQuery编程,并希望在编写这段代码时寻求帮助。

有几个 li 项目的 ul 列表。每个 li 都具有以下结构

 <li><a href="http://www.findadeal.com/city-state/"/>City</li> 

其中city-state和City是任何城市的硬编码值,比如说

 <li><a href="http://www.findadeal.com/buffalo-ny/"/>Buffalo</li>

当请求页面时,在查询字符串中发送产品分类参数,例如“beer”。

我需要修改 li 链接,以便在页面加载期间获取以下表单。

 <li><a href="http://www.findadeal.com/buffalo-ny/beer/"/>Buffalo Beer</li>

如何使用jQuery对循环逻辑进行编码,以便相应地修改每个 li 元素。页面上通常不超过50个城市。

谢谢。

2 个答案:

答案 0 :(得分:0)

在jQuery中,您可以将text()函数传递给另一个函数,该函数的返回值将是当前元素的新值。

//wait for document.ready to fire before doing anything
$(function () {

    //check to see if there is a query-string or not
    if (window.location.search != '') {

        //split the query-string by ampersands
        var parameters = window.location.search.replace('?', '').split('&');

        //iterate through the query-string key/value pairs
        for (var i = 0, len = parameters.length; i < len; i++) {

            //get the key/value pair split into an array
            var pair = parameters[i].split('=');

            //if the key is the correct one then we can proceed
            if (pair[0] == 'product-classification') {

                //update each `li` element with the value of the `product-classification` query-string variable
                $('li').text(function () {

                    //add the value to the current text of the `li` element
                    return $(this).text() + ' ' + pair[1];
                });

                //now we can stop the loop because we have done what we want, if there are lots of query-string parameters this will be a good idea
                break;
            }
        }
    }
});

以下是演示:http://jsfiddle.net/LQXWz/

.text()的文档:http://api.jquery.com/text

答案 1 :(得分:0)

我不完全确定你在寻找什么,但我认为这可能会让你在路上。

$('li').each(function(){ //grab all li elements and loop through them
   var $this = $(this); //capture the jquery object for use later
   $this.find('a').attr('href','your new text');
});