如何在javascript中使用<select>标记ID。当id是PHP数组时?

时间:2016-03-12 17:21:32

标签: javascript php jquery html

我有HTML&lt; select&gt;标签ID。我需要使用javascript跟踪,选择了哪个选项 我的html&lt; select&gt; ID: &lt; select id =“&lt;?php echo $ userArray [$ key] [”userID“]?&gt;”&gt; 我的javascript代码: &lt; script type =“text / javascript”&gt;     $(文件)。就绪(函数(){         $( '#selectionButton')。点击(函数(){             var selectedValue = $(“#&lt;?php echo json_encode($ userArray [$ key] ['userID']);?&gt;”)。val();             window.alert(了selectedValue);         });     }); 如何在JavaScript中使用PHP数组作为HTML id?

1 个答案:

答案 0 :(得分:1)

这里的要点不仅仅是使用PHP array值作为您的潜在事件目标标识符,它通常是关于使用动态生成的数据作为元素的一部分&#39; id个属性。在这里,您最好在JS中定位class而不是id。因此,当事件触发时,您检查目标的id值。

$(document).on('click', '.i-am-target-class', function () {
    var targetId = $(this).attr('id');
    // do your stuff knowing id
});

你想把你的PHP代码作为你的事件目标传递给你的东西远远不是市场上最好的解决方案

<强> UPD:

PHP:
<select id="<?php echo $userArray[$key]['userID']; ?>" class="value-to-save"></select>

JS:
var results = {};

$('#save-button').click(function () {
    $('.value-to-save').each(function () {
        var userId = $(this).attr('id');
        var value = $(this).val();
        results[userId] = value;
    });
});

因此,最终您将获得包含所有数据的results对象