简体   繁体   English

JavaScript在同一个ID上有多个值

[英]Javascript multiple values on the same ID

I have a loop in php that echos out a <input type="hidden" id="lol" value=$id /> 我在php中有一个回显<input type="hidden" id="lol" value=$id />的循环

Every time the loops go through i get a new value in the hidden input field as you can understand. 您可以理解,每次循环经过时,我都会在隐藏的输入字段中得到一个新值。

Now, im trying to grab the value from each of these items and get grab it with Javascript and SAJAX. 现在,即时通讯试图从这些项目的每一个中获取价值,并使用Javascript和SAJAX来获取它。 The javascript im using now works, But! 使用的javascript im现在可以正常工作,但是! It only grabs the first value (because the ID is the same on each input) 它仅获取第一个值(因为每个输入的ID相同)

Javscript: 字幕:

function Showbooking() {
    id = document.getElementById('lol').value;
    x_showBookingForm(id, do_showBookingForm);
}
function do_showBookingForm(html) {
    openPopup(600, 550, html);
}

As you can see im opening a POPUP with javascript aswell and exports the value into that popup window. 如您所见,im也会使用javascript打开POPUP并将值导出到该弹出窗口。

So on every popup I get the same value (the value from the first input). 因此,在每个弹出窗口上,我都得到相同的值(第一个输入的值)。

How Do I get around this problem? 我该如何解决这个问题?

  1. Change ID to name 将ID更改为名称
  2. Use document.getElementsByName and loop 使用document.getElementsByName并循环
var lols = document.getElementsByName("lol");
var vals=[];
for (var i=0, n=lols.length;i<n;i++) {
  vals.push(lols[i].value);
}
alert(vals.join(","));

getElementById says element rather than elements because it returns only one item. getElementById表示元素而不是元素,因为它仅返回一项。 id is supposed to be unique. id应该是唯一的。 You could do something to the effect of: 您可以采取以下措施:

var inputs = document.getElementsByTagName("input");
var values = [];
for(var i=0;i<inputs.length;i++){
    if(inputs[i].type === "hidden"){
        values.push(inputs[i].value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM