首页 > 解决方案 > 如何发送到 Javascript 表单元素值。不断发送一个值

问题描述

<script>
function tikla()
{
	//var radio=document.getElementById('radio').value;
	var d2=document.getElementById('buton').value;
	alert(d2);
}
</script>
<?php 

	for($i=1;$i<5;$i++)
	{?>
    	<form>
        <?php echo $i; ?>
            <input type="text" name="txt" value="<?php echo $i; ?>" disabled="disabled" /> 
          	<input type="button" id="buton" value="<?php echo $i; ?>" onclick="tikla(this.value)" />
         </form>
	<?php }?>

在 PHP 中,我想将按钮或文本值发送到 Javascript,但我只能发送一个值。我看不到其他循环值。

标签: javascriptphploopsfor-loop

解决方案


Is it really the intention to have multiple forms? There is no reason why not of course but you can accomplish what you need, generally speaking, using a single form.

By using a nodelist you can iterate through and assign event listeners separately to the HTML - inline event handlers are considered old school nowadays. In this example the event handler is assigned to each button and simply alerts the numeric value assigned to the button ( as in your example ) and also the value and type of the text field to show how you might access it if required.

A quick demo

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>JS Func</title>
        <style>
            fieldset{border:none;margin:1rem auto}
        </style>
    </head>
    <body>
        <form>
        <?php
            for( $i=1; $i<5; $i++ ) {
                $rand = rand(1,99);
        ?>
                <fieldset>
                    <?php echo $i; ?>
                    <input type='text' name='txt[]' value='<?php echo $i * $rand; ?>' /> 
                    <input type='button' value='<?php echo $i; ?>' />
                </fieldset>
        <?php
            }
        ?>
        </form>
        <script>
            Array.prototype.slice.call( document.querySelectorAll( 'form > fieldset > input[type="button"]' ) ).forEach( function( bttn ){
                bttn.addEventListener('click', function(event){
                    alert( this.value  +' '+this.previousElementSibling.value + ' ' +this.previousElementSibling.tagName )
                }, false );
            })
        </script>
    </body>
</html>

推荐阅读