Javascript在< span>元件 [英] Javascript get text inside a <span> element

查看:133
本文介绍了Javascript在< span>元件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到一个元素内的文本。



我只能抓取这个元素的类,而不是ID。

 < span class =fileName> test.png< / span> 

所以我需要一种方法来获得 test.png ,但是你看到我只有元素的类而不是ID。



还要注意,我们可能有更多 ; span class =fileName>< / span> ,因此它可能如下所示:

 < span class =fileName> test1.png< / span> 
< span class =fileName> test2.png< / span>
< span class =fileName> test3.png< / span>
< span class =fileName> test4.png< / span>

在这种情况下,我们需要获得所有的值,只有一个,因为我需要传递这个值到另一个页面与jQuery。因此,它应该能够从该元素中获取一个或多个值。



请帮助!



$

  var filenames = $('。fileName') ).map(function(){
return $(this).text();
})。

数组 filenames 将包含所有名称的图像。您可以将此数组传递给另一个jQuery函数,或者您喜欢的其他任何地方。



您可以在这里进行测试»



更新



文件名是一个用逗号分隔的字符串,可以这样做:

  var filenames = $('。fileName' ).map(function(){
return $(this).text();
})get()。

现在, filenames 将包含字符串 test1.png,test2.png,test3.png,test4.png


I need to get the text that is inside a element.

I can only grab the class of this element and NOT the ID.

<span class="fileName">test.png</span>

So I need a way to get test.png, but as you see I have only the class of the element and not the ID.

Just notice also that we may have more <span class="fileName"></span>, so it could look like this

<span class="fileName">test1.png</span>
<span class="fileName">test2.png</span>
<span class="fileName">test3.png</span>
<span class="fileName">test4.png</span>

In the case we have more, like the example above, I need to get ALL the values and not only one, because I need to pass this value to another page with jQuery. So it should be able to get one value or more from that element.

Please help!

And also I am not a javascript expert!

解决方案

var filenames = $('.fileName').map(function(){
    return $(this).text();
}).get();

The array filenames will contain all the names of the images. You can pass on this array to another jQuery function, or anywhere else you like to do so.

You can test it here »

Update

Since you request the filenames to be a string separated by a comma, you can do it like this:

var filenames = $('.fileName').map(function(){
    return $(this).text();
}).get().join(',');

Now, filenames will contain the string test1.png,test2.png,test3.png,test4.png.

这篇关于Javascript在&lt; span&gt;元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆