计算<pre> tag using php or jquery</pre>中的字数

时间:2014-04-16 09:51:46

标签: javascript php jquery

我想计算以下声明中的字词:

<pre id="output" class="output">["PHP","Python"]</pre>

然后我需要通过POST(提交按钮)将每个单词分配给PHP变量

当单词在[“”,“”]标签内时,我不知道如何计算PHP或JQuery?我有一个插件(无法编辑代码),如上所述填充预标签。

提前致谢

西蒙

2 个答案:

答案 0 :(得分:1)

HTML:

<pre id="output" class="output">["PHP","Python"]</pre>
<form method="post" target="#" id="myForm">
    <input type="submit"/>
</form>
<textarea id="result" style="width:400px; height:200px;">
</textarea>

jQuery的:

//get rid of the brackets and split the vars with the comma as a delimiter
var varsArray= $("#output").html().split('[')[1].split(']')[0].split(',');

//count the elements:
var total = $(varsArray).length;

$(varsArray).each(function(idx,value){
    // the each function provides id and value, you use those to create a hidden field
    // in your form and set its name using the id, and value using the value 
    $("#myForm").append('<input type="hidden" name="var'+idx+'" value='+value+'>\n\r');
});

//print the new form's content into the text area just to see what it will look like
$("#result").val($("#myForm").html());

这里有一个jsfiddle的例子,我希望它有所帮助:

http://jsfiddle.net/TheBanana/AD8x9/

答案 1 :(得分:0)

首先你需要得到pre的内容:

jQuery示例:

var contents = $("#output").html();

//now you could need to remove "[" and "]":

contents = contents.replace("[","").replace("]","");
var elements = contents.split(",");

//now you will have to check the length of "elements"

var count = elements.length;