JS:最后一个输入元素的名称(HTML/PHP)


JS: name of last input element (HTML/PHP)

我最好列一个清单来解释我想做的步骤:

  1. 获取html输入的最后一个元素的名称(已通过PHP生成)

基本设置如下:

<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
  1. 将其传递给JS函数
  2. 附加一些附加字段(使用名称的一部分作为新字段的id

JS脚本运行良好,我可以添加字段。此外,PHP脚本正在处理字段的内容,并将其写入数据库中。

Short:无论有多少个字段,我都如何获得最后一个值?

edit:我忘了有一个提交按钮,它也会作为最后一个元素出现。。。抱歉

有很多方法,但鉴于所有其他答案都依赖于jQuery库(这增加了不必要的开销),我将重点展示一些简单的JavaScript方法(适用于IE8+以上的最新浏览器)。

var allTextInputs = document.querySelectorAll('input[type="text"]'),
    lastInput = allTextInputs[allTextInputs.length - 1],
    lastInputName = lastInput.name;

var allInputsTxt = document.querySelectorAll('input[type="text"]');
var lastInput = allInputsTxt[allInputsTxt.length - 1];
var lastInputName = lastInput.name;
var lastInputValue = lastInput.value;
alert('last input name : ' + lastInputName + '; last input value : ' + lastInputValue);
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>

如果您想要的是,而不是name属性,请在使用与上面相同的方法获得最后一个<input type="text"/>:的名称后执行此操作

var lastInputValue = lastInput.value;

这些方法将在代码运行时给出文档中type="text"的最后一个<input />的值;要找到动态添加到文档中的最后一个<input />的值,您需要在插入该元素后重新运行一种工作方法。

jQuery。。。
var lastInputName = $('input[type="text"]:last').attr('name');

下面的jQuery代码应该可以做到这一点。

var lastValue = $("input[type=text]:last").val();

还有jQuery:

var $inputs = $("input[type=text]");
var lastValue = $inputs[$inputs.length - 1].value;

将CSS3选择器与sizzle(jquery)结合使用以针对最后一个元素

var name = $('input[name^=E_]:last')[0].name

PHP或JavaScript中的最后一个值?在PHP中,字段通常作为数组传递,因此可以使用获得最后一个值

end($array)

如果你像这个一样命名你的档案,那就更好了

<input type='text'name='E[8]' value= '123' />
<input type='text'name='E[9]' value= '456' />
<input type='text'name='E[10]' value= '789' />

在JS中,您需要将字段放入一个数组中,然后获得最后一个。。。。你需要这样的

var myFields = document.forms["myform"].getElementsByTagName('input'),
var lastValue = myFields[(myFields.length-1)].value;

通过将代码包装为父元素,假设使用属性id="inputs",这里有一个普通的DOM(无jQuery)解决方案:

// start by finding the last-most element
var lastInput = document.getElementById('inputs').lastElementChild;
// search backward to the last 'text' element
while (lastInput && lastInput.type !== 'text') {
    lastInput = lastInput.previousElementSibling;
}
// and get its value
var lastValue = lastInput ? lastInput.value : null;

这个解决方案有趣的部分是不创建数组,这样可以节省一些JavaScript内存。它应该可以与Firefox,Chrome和IE 9兼容。