简体   繁体   English

按名称获取具有$ key的元素

[英]Get element by name which has $key

PHP PHP

<input type="number"  min="0" max="500" value="" name="qty<?php echo $key ?>" id="<?php echo $key ?>" onChange="findTotal()" />

JS JS

function findTotal() {
    var arr = document.getElementsByName('qty');
    ....
}

How do I get element by name which has $key inside? 如何通过名称获取其中包含$key元素?

Let's say $key is 'x'. 假设$ key是'x'。 You could then use getElementbyID('x'), because echoing $key is the same as putting id="x". 然后,您可以使用getElementbyID('x'),因为回显$ key与放置id =“ x”相同。

Oh, I see. 哦,我明白了。 you have series of rows with the different qty keys. 您有一系列具有不同数量键的行。

then try this. 然后试试这个。

in PHP: 在PHP中:

<input type="number" min="0" max="500" value="" name="qty<?php echo $key ?>" id="<?php echo $key ?>" onChange="findTotal('qty<?php echo $key?>')" />

and in JS: 在JS中:

 function findTotal(key) {
    var arr = document.getElementsByName(key);
    ....
}

You can assign this as your function params then you can call its name or id from your function when onchange event executed !! 您可以将this作为你的函数,那么PARAMS你可以从你的函数时onchange事件执行调用它的名称或ID!

//assign this
<input type="number"  min="0" max="500" value="" name="qty<?php echo $key ?>" id="<?php echo $key ?>" onChange="findTotal(this)" />

function findTotal(current) {
  var arr = current.name; // current.id for id
  alert(arr);    
}

Since your name is dynamic, you can not get the element by the name unless your JS has some way of knowing that dynamic name (such as if you have a list of them and are running them in a loop). 由于您的name是动态的,因此除非您的JS有某种了解动态name (例如,如果您具有它们的列表并且正在循环运行它们),否则您无法通过name获取元素。

In your case, you may want to try using data attributes as outlined here: Mozzila - Using data attributes 对于您的情况,您可能想要尝试使用此处概述的data属性: Mozzila-使用数据属性

You may also be able to take advantage of this as outlined in this answer: Javascript Get Element Value - Answer By yorick 您还可能能够利用this作为这个答案概述: 使用Javascript获取元素值-回答的yorick

Let me know if this helps. 让我知道是否有帮助。 I may be able to refine this answer if you can give some more information about your specific implementation. 如果您可以提供有关特定实现的更多信息,我也许可以完善此答案。

Cheers! 干杯!

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

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