Pergunta

I'm getting all input texts in my HTML page by using this:

 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.

I'm trying to do something similar but with all my spans. I have this in my HTML file:

 <td class="name"><span>{%=file.name%}</span></td>

I can have as many <td class="name"> ... tags as I want. 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.

How can I do it?

Foi útil?

Solução 2

Iterate over .name (or specifiy deeper if necessary), build your data structure (using data), and then convert it to JSON. Working example: http://jsfiddle.net/tLuPC/

Below is simulating id if you needed to obtain that as mentioned in your post. Using data- attribute to store info. Otherwise you can simply just obtain the 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));

Outras dicas

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').each(function(index,val){
   //do something with val
});

you can see a reference to this method here.

Simple fiddle: http://jsfiddle.net/CMdBa/1/

You can use a map function to enumerate and format a collection.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top