开发者

Trigger Image Creation from Input field's text

A user types words into an input field, after clicking the Go button, little images with file names开发者_Go百科 that match the keywords pop up in a certain place in the hierarchy. I just wanted someone to double check this script to see if there's any bugs in it, as it doesn't appear to work. The input is a comma separated list, hence the trim.

$(".Go").live('click', function(){
    var words = [];
    jQuery.each(jQuery.trim(jQuery("#input").val()).split(","), function(index, value){
        words.push(jQuery.trim(value));
    });

    for(i=0; i > words.length(); i++){
        $('#Place').append('img').attr("src", words[i]+'.png');
    }
});

Thanks goes out to Femi, who formulated this script for me.


Here's a working demo with various improvements.

The reasons your code won't work are:

  • i > words.length() will always be false as you're initially setting it to 0, that needs to be <.

  • length is a property, not a function. Remove the brackets.

  • Your syntax for appending a new img element just appends a string of 'img'. In order to use append() to append a new element like that, you'll need to use the overload that takes a function.

  • Not strictly a bug, but there's a lot of unnecessary code in there. split() returns an array already, so looping through that array to put each array element into another array is redundant. There's also no reason to new up the words array before assigning it.

  • There's no particular reason to use live() if you're not dynamically adding elements with a class of go. You could simply use click() instead.


EDIT:
In answer to the comments, here's how to add the images to two different containers based on the word.

EDIT 2:
and to add the image to a different container based on whether the 'word' is upper case, lower case, numbers or symbols (ie: none of the above!)


Looks like the condition has a couple typos

i > words.length()

This will never be true and length is a property. Should be:

for(i=0; i < words.length; i++)


Yes, definitely a typo there. Here's a good guide, with they typo corrected, to help you along with your script: http://jsfiddle.net/vkSQy/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜