所以我有一个基本的下拉列表,每个下拉选项都有特定的属性。我想将这些属性(数据名称,描述和值)传递给javascript函数。代码在控制台下面,对于我想要传递的所有东西都说“未定义”。我已经尝试将.data()
更改为.attr()
。我真的需要干净简单的东西。谢谢!
<label class="dropdown" style="float: left" >
<div class="dd-button">Select a Plan</div>
<input type="checkbox" class="dd-input" id="test">
<ul id="dropdown" class="dd-menu">
<li data-description="description." data-name="Web" data-value="mmk">2</li>
<li data-description="description." data-name="Basic" data-value="basic">3</li>
<li data-description="description." data-name="Plus" data-value="plus">4</li>
</ul>
</label>
var PLAN_CONFIG = {
id: '',
billing: '',
name: '',
description: '',
payment: true,
panelLabel: 'Confirm',
};
$('#dropdown').click(function () {
PLAN_CONFIG.id = $(this).data('value');
PLAN_CONFIG.name = $(this).data('name');
PLAN_CONFIG.description = $(this).data('description');
console.log(PLAN_CONFIG);
});
答案 0 :(得分:6)
如果您将点击事件处理程序分配给#dropdown
,则回调函数中的this
也将为#dropdown
。您应该将事件处理程序分配给li
元素:
$('#dropdown li').click(function () {
演示:
var PLAN_CONFIG = {
id: '',
billing: '',
name: '',
description: '',
payment: true,
panelLabel: 'Confirm',
};
$('#dropdown li').click(function () {
PLAN_CONFIG.id = $(this).data('value');
PLAN_CONFIG.name = $(this).data('name');
PLAN_CONFIG.description = $(this).data('description');
console.log(PLAN_CONFIG);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="dropdown" style = "float: left" >
<div class="dd-button"> Select a Plan </div>
<input type="checkbox" class="dd-input" id="test">
<ul id = "dropdown" class="dd-menu">
<li data-description = "description." data-name = "Web" data-value="mmk" >2 </li>
<li data-description = "description." data-name = "Basic" data-value="basic" >3 </li>
<li data-description = "description." data-name = "Plus" data-value="plus" >4</li>
</ul>
</label>
答案 1 :(得分:3)
使用此选择器'#dropdown li'
。
您当前的代码将点击事件绑定到您的元素dropdown
而不是li
元素。
var PLAN_CONFIG = {
id: '',
billing: '',
name: '',
description: '',
payment: true,
panelLabel: 'Confirm',
};
$('#dropdown li').click(function() {
PLAN_CONFIG.id = $(this).data('value');
PLAN_CONFIG.name = $(this).data('name');
PLAN_CONFIG.description = $(this).data('description');
console.log(PLAN_CONFIG);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="dropdown" style="float: left">
<div class="dd-button"> Select a Plan </div>
<input type="checkbox" class="dd-input" id="test">
<ul id = "dropdown" class="dd-menu">
<li data-description = "description." data-name = "Web" data-value="mmk" >2 </li>
<li data-description = "description." data-name = "Basic" data-value="basic" >3 </li>
<li data-description = "description." data-name = "Plus" data-value="plus" >4</li>
</ul>
</label>
&#13;