javascript - 如何发送到 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,但我只能发送一个值。我看不到其他循环值。
解决方案
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>
推荐阅读
- rabbitmq - 使用rabbitMq服务器基于IP地址的用户限制
- javascript - 我有 2 个 UI 选项卡。我需要在单击该选项卡外的按钮时激活一个特定选项卡
- ios - Wkwebview 无法在具有库目录路径的 html 中显示图像
- reactjs - 如何在 React js 中读取 xml 文件(data.xml)?
- php - laravel 5:HTML标签在刀片文件中不起作用
- java - MapView:二进制 XML 文件第 13 行:二进制 XML 文件第 13 行:膨胀类错误
- python - 在 python 中部署 azure 函数不会从 requirements.txt 安装依赖项
- java - 将公式放入 for 循环
- python - IndexError:python中的循环列表索引超出范围
- vue.js - 如何在 Vue js 组件中添加 javascript 分页代码