开发者

jQuery plugin in theory

I'm planning to build small plugin in jQuery 开发者_如何转开发- just want to check your opinion whether jQuery is the tool for the job.

Basically, I would have two textareas, where I would enter strings (comma or new line separated).

e.g:

textarea 1 content: 1,2,3,4

textarea 2 content: a,b,c,d

After pressing submit I would like jQuery to create every possible combination ( 1a,1b,1c,1d,2a,2b etc....) and return that in a->z order.

Q1. Can jQuery detect new line?(without html mark-up)

Q2. Every list will have 100 - 1000 entries. Will jQuery cope with it?

Q3. Do you know any jQuery function which do something like every possible combination or would that be for loop?

Any suggestions much appreciated.


A simple implementation:

function getValues( id1, id2, delimiter ) {    
    var elem1, elem2,
        arr1, arr2,
        i, j, 
        result = [];

    elem1 = document.getElementById( id1 );
    elem2 = document.getElementById( id2 );
    arr1 = elem1.value.split( delimiter );
    arr2 = elem2.value.split( delimiter );

    for ( i = 0; i < arr1.length; i += 1 ) {
        for ( j = 0; j < arr2.length; j += 1 ) {
            result.push( arr1[i].trim() + arr2[j].trim() );
        }
    }

    return result.sort().toString();
}

Live demo: http://jsfiddle.net/YvgAM/5/

Explanation:

This function accepts three parameters:

  • the first two parameters are ID names of the two TEXTAREA elements,
  • the third parameter is the delimiter (string), eg. ',', '\n'.

First, you get the elements, then you grab their contents (the text) and split that into an array using the supplied delimiter.

Now, you just use two nested for loop to construct an array of values.

Last, you sort that array and cast it into String.


This sounds like a good job for jQuery; in general, jquery plugins are useful when you want something highly reusable that you can instantiate with $("some-selector").make_my_custom_thing();

  1. jQuery doesn't provide any native way to detect newlines, you'll need to split the strings yourself over whichever character you like (either commas, new lines, white space, etc).

  2. I'd be less concerned here with jQuery couping with your objects and more with how your code handles it. jQuery provides iterators over collections, but you write the function that it calls on each element. Make sure the function you pass to jQuery.each is fast enough for your purposes.

  3. If you're not concerned with uniqueness, you can just use a nested loop. Eg:

(psuedo-code)

combinations = [];
for (var i in collection_1) {
  for (var j in collection_2) {
    combinations.append(i + j); //assumes string addition
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜