当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jQuery .hide() does not work with my array

问题描述:

Hello and thanks for your help.

I have a php script on my website that returns my last few tweets in form of an unordered list with the posts each being a list item.

<div id="latesttweet">

<ul>

<li>

This is a tweet<br />

<span>3 hours ago.</span>

</li>

<li>

This is another tweet<br />

<span>4 hours ago.</span>

</li>

</ul>

</div>

I tried to hide some of them dynamically using JavaScript, but for some reason once I collect all the list items in an Array, I can't address them properly anymore. When I alert the length of the Array however, I get the right number.

jQuery seems to be working alright in general.

var activeTweet = 0;

var tweet_ul = document.getElementById('latesttweet');

var tweetArray = tweet_ul.getElementsByTagName('li');

var tweetCount = tweetArray.length;

alert(tweetCount); //returns the right result

tweetArray[1].hide();

This way, one should expect that the second list item would have display set to none, but still both items remain visible.

What am I doing wrong?

网友答案:

Basically you are not using jQuery

$(tweetArray[1]).hide()
网友答案:

Your array are DOM objects, not jQuery objects. Try the following:

var activeTweet = 0;
var tweet_ul = $('#latesttweet');
var tweetArray = $('li');

var tweetCount = tweetArray.length;
alert(tweetCount); //returns the right result

tweetArray[1].hide();
网友答案:

Try this:

$(tweetArray[1]).hide();
网友答案:
tweetArray[1].style.display="none";
网友答案:
$(tweetArray[1]).hide();

This should do the job. tweetArray[1] is just an html element and it does not have hide() method defined for it.

网友答案:

hide() is part of jQuery. You have to use the $() method: $(tweetArray[1]).hide().

网友答案:

You will have to wrap tweetArray[1] into a jquery object

Try

$(tweetArray[1]).hide();

网友答案:
var tweets = $( '#latesttweet ul' ).children( 'li' ); 
$( tweets[1] ).hide();

http://jsbin.com/usiyex/2/

分享给朋友:
您可能感兴趣的文章:
随机阅读: