【发布时间】:2021-08-17 16:41:38
【问题描述】:
我的 PHP 数组中有数据,我想将其转换为按钮。
为简单起见,这些按钮将在点击时console.log() 他们的数据。
现在我正在使用内联事件处理程序来执行此操作。
如何使用数据属性而不使用内联事件处理程序来解决此问题?我知道如何创建数据属性,但我不知道如何记录数据并将事件侦听器绑定到按钮。
<script>
function logData(lat, long) {
console.log(lat);
console.log(long);
}
</script>
<?php
$coordinates = array(
first => array(
"lat" => "64",
"long" => "89"
),
second => array(
"lat" => "23",
"long" => "11"
),
third => array(
"lat" => "35",
"long" => "76"
)
);
// Create buttons with inline event handlers
foreach($coordinates as $point) {
echo "<button onclick='logData(".$point["lat"].", ".$point["long"].")'>Button</button>";
}
echo "<br><br>";
// Create buttons with data attributes. How do you log the data without inline event handlers?
foreach($coordinates as $point) {
echo "<button data-lat=".$point["lat"]." data-long=".$point["long"].">Button</button>";
}
?>
【问题讨论】:
标签: javascript php html jquery css