0

我有这个:

<?php $i=0;?>
<?php foreach($x as $y): ?>
<input type="hidden" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
<?php $i = $i + 1; ?>
<?php endforeach; ?>

我需要像这样获取每个“theid”的值:

<script type="text/javascript">
function somefunction(element, optionTitle) {
var num = document.getElementById('theid').value;
...
</script>

考虑到“theid”添加了 $i 的事实,我该怎么做?谢谢。

4

3 回答 3

1

如果您有多个输入字段并且您想对多个输入字段执行相同的操作,您可以使用getElementsByClassName代替getElementById

PHP

<input type="hidden" class="theclassname" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>

JS:

<script type="text/javascript">
    function somefunction(element, optionTitle) {
        var myEles = document.getElementsByClassName('theclassname');
        // loop over myEles and act on each one
        for (var i=0; i < myEles.length; i++) {
            alert("Input with id: " + myEles[i].id + " has value: " + myEles[i].value);
        }
    }
</script>
于 2013-03-26T20:38:49.310 回答
0

我建议使用 jQuery,jQuery 选择器支持通配符:

$('input[id^=theid]')

有关此主题的进一步阅读,请参阅http://api.jquery.com/category/selectors/

于 2013-03-26T20:41:39.123 回答
0

如果你使用 jQuery 会很简单:

$('input[id^="theid"]').each(function () {
  console.log($(this).val()); //value of each theid
});

这是一个jsBin

于 2013-03-26T20:46:35.633 回答