[英]How do I get all spans created in my HTML page using jQuery
I'm getting all input texts in my HTML page by using this: 我通过使用以下命令在HTML页面中获取所有输入文本:
var inputs = data.context.find(':input');
$('#result').text(JSON.stringify(inputs.serializeArray()));
Then I have an JSON string with id and value of each input text. 然后,我有一个ID为每个输入文本的ID和值的JSON字符串。
I'm trying to do something similar but with all my spans. 我正在尝试做类似的事情,但跨度很大。 I have this in my HTML file:
我的HTML档案中有这个:
<td class="name"><span>{%=file.name%}</span></td>
I can have as many <td class="name"> ...
tags as I want. 我可以根据需要设置任意多个
<td class="name"> ...
标签。 So I have to get the value of all of them and convert to an JSON string as I did with the input text above. 因此,我必须获取所有参数的值,然后像上面输入文本一样将其转换为JSON字符串。
How can I do it? 我该怎么做?
this code snippet: $('.name span')
will return an array of objects, so in order to get the text from each one you need to run on it as an array: 此代码段:
$('.name span')
将返回一个对象数组,因此,为了从每个对象中获取文本,您需要将其作为数组运行:
$('.name span').each(function(index,val){
//do something with val
});
you can see a reference to this method here . 您可以在此处看到对此方法的参考。
Simple fiddle: http://jsfiddle.net/CMdBa/1/ 简单的提琴: http : //jsfiddle.net/CMdBa/1/
Iterate over .name
(or specifiy deeper if necessary), build your data structure (using data
), and then convert it to JSON. 遍历
.name
(或在必要时指定更深的深度),构建数据结构(使用data
),然后将其转换为JSON。 Working example: http://jsfiddle.net/tLuPC/ 工作示例: http : //jsfiddle.net/tLuPC/
Below is simulating id
if you needed to obtain that as mentioned in your post. 如果您需要获得帖子中提到的
id
则下面是模拟id
。 Using data-
attribute to store info. 使用
data-
属性存储信息。 Otherwise you can simply just obtain the name
. 否则,您只需获取
name
。
var data = [],
jsonData = null;
$('.name').each(function () {
var item = $(this);
data.push({
id: item.data('id'),
name: $('span', item).text()
});
});
jsonData = JSON.stringify(data);
console.log(JSON.stringify(jsonData));
You can use a map
function to enumerate and format a collection. 您可以使用
map
函数来枚举和格式化集合。
var spanTextArray = $('td.name span').map(function(){
return $.trim(this.innerHTML);
}).get();
This will output an array of file names, you could easily modify the return to output an array of key value pairs. 这将输出一个文件名数组,您可以轻松修改返回值以输出键值对数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.