开发者

Matching a String and then incrementing a number within HTML elements

I have tags in a html list, here is an example of two tags.

<div class="tags">
    <ul>
        <li>
            <a onclick="tag_search('tag1');" href="#">tag1
                <span class="num-active">1</span></a>
        </li>
        <开发者_开发问答;li>
            <a onclick="tag_search('tag2');" href="#">tag2
                <span class="num-active">1</span></a>
        </li>
    </ul>
</div>

I would like to write a function that I can pass a string to, that will match the strings in the a hyperlink i.e. "tag1" or "tag2", if there is a match then increment the number in the span, if not then add a new li.

The bit I am having trouble with is how do I search for a string in the div with class tags and then when I find a match identifying the element. I can't even do the first bit as I am use to using an ID or a Class.

I appreciate any help on this using JQuery

Thanks all

Code so far

function change_tag_count(item){

    alert(item);//alerts the string test

    $.fn.searchString = function(str) {
        return this.filter('*:contains("' + item + '")');
    };

    if($('body').searchString(item).length){

        var n = $('a').searchString(item).children().text();

        n = parseInt(n) + 1; 

        $('a').searchString(item).children().text(n);

    }else{
        alert('here');//does not alert this when no li contains the word test
        $("#all_tags ul").append('<a onclick="tag_search(\''+item+'\');" href="#">'+item+'<span class="num-active">1</span></a>');    

    }

}


The solution you have so far is very inefficient. You might have more luck using an object to keep track of the tags so far, like so:

var tags = {}; // This will memoize the tags we already have
function tagSearch(text) {
  var $match;
  if (tags.hasOwnProperty(text)) {
    $match = tags[text]; // use the one we stored earlier
  } else {
    $match = $([
      '<li><a href="#" onclick="tagSearch(\'', text, '\'); return false;">',
      text, ' <span class="num-active">0</span></a></li>'
    ].join('')).appendTo($('#all_tags ul'));
    tags[text] = $match; // hold onto this for next time
  }

  var $countSpan = $match.find('span.num-active');
  var count = parseInt($countSpan.text(), 10) + 1;
  $countSpan.text(count);
}

I am not sure what your eventual goal is with this code. Depending on what you want to do with it, there are probably much more elegant ways to write this code that would allow you to avoid having to stash onclicks on elements themselves, but I stuck to the way you were already writing it for now.

I did test this code, and it appears to be working, given my understanding of your requirements.


I didn't test this code but it should work. I would recommend making it easier on your browser and giving each li and ID to avoid the $.each() as you could accomplish the same thing simply with a $("#item").length

function tagSearch(item) {
    $(".tags").find("li").each(function() {
        if($(this).find("a").text() == item) {
            var n = $(this).find("span").text();
            n = parseInt(n) + 1;
            $(this).find("span").text(n);
        } else {
            $(this).parent().append('<li>some html stuff</li>');
        }
    });
}


Just use the jQuery :contains selector:

var $matchingElements = $('*:contains("Foo")');

Here’s a quick plugin that does what you want:

$.fn.searchString = function(str) {
 return this.filter('*:contains("' + str + '")');
};

Use it as follows:

// Return all `a` elements in the DOM containing the string 'Foo' as a chainable jQuery object
$('a').searchString('Foo');
// E.g.
$('a').searchString('Foo').addClass('highlight');


Here's what I'm thinking. First off, change the div's class to an ID. Then:

<script language="javascript" type="text/javascript">
function tagSearch(tagToFind){
    var found=0;
    $("#tags>ul>li").each(function(index){
    if ($(this).children("a").html().indexOf(tagToFind)!=-1 && !found)
    { 
        var spanNum=parseInt($(this).find("span").html());
        $(this).find("span").html((spanNum+1));
        found=1;
    }
    else if (index==$("#tags>ul>li").last().index() && !found)
    {
        $("#tags>ul").append('<li><a href="#">tag'+(index+1)
              +' <span class="num-active">1</span></a></li>');
    }
});
}

</script>
</head>
<body>
<div id="tags">
    <ul>
        <li>
            <a onclick="tagSearch('tag1');" href="#">tag1
                <span class="num-active">1</span></a>
        </li>
        <li>
            <a onclick="tagSearch('tag2');" href="#">tag2
                <span class="num-active">1</span></a>
        </li>
    </ul>
</div>
</body>

Then I'd set up your event structure to automatically perform this action if you click on one of those links. The part I don't understand is how you'd have an li that DIDN'T get matched...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜