Javascript 选择2编程访问
我使用jQuery时遇到了一个问题,设置了一个值并触发了一个事件 我有一个简单的select2下拉列表,连接到Ajax源代码。这个很好用 我还有一个事件等待选择select2选项:Javascript 选择2编程访问,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我使用jQuery时遇到了一个问题,设置了一个值并触发了一个事件 我有一个简单的select2下拉列表,连接到Ajax源代码。这个很好用 我还有一个事件等待选择select2选项: // On project select, we add the projects to the list along with the parties $('.projSearch').on("select2-selecting", function(e) { // Set the value of t
// On project select, we add the projects to the list along with the parties
$('.projSearch').on("select2-selecting", function(e) {
// Set the value of the project
var projectID = e.val,
table = '';
alert(projectID);
console.log(e);
...
像正常情况一样使用select2下拉列表时,此事件工作正常。它检测您选择的选项的数据
但是,我还在页面上添加了一个按钮,允许用户设置字段的数据。它可以很好地设置数据,但不会触发事件select2 selection
我尝试将数据与事件一起传递,但无论何时触发select2 selection
事件,它都会返回undefined
$(document).on("click", "[name=addProject]", function() {
// Set the vars
var projectName = $(this).attr('projectname'),
projectID = $(this).attr('projectid'),
projectNameLong = projectName + ' ('+projectID+')';
// Add the project to the list
$("[name=projects]").select2("data", [{id: projectID, text: projectNameLong}]).trigger("select2-selecting", {val: projectID, data: {id: projectID, text: projectNameLong}});
});
我如何将数据与触发器一起传递给我可以在事件中访问的对象
谢谢你提供的任何信息 使用包含要查找的val
和data
属性的自定义数据选择2 by。将允许您直接从事件处理程序中获取额外数据,但不会将其附加到事件对象
$(document).on("click", "[name=addProject]", function() {
// Set the vars
var projectName = $(this).attr('projectname'),
projectID = $(this).attr('projectid'),
projectNameLong = projectName + ' ('+projectID+')';
// Create the data object
var data = {
id: projectID,
text: projectNameLong
};
// Create the custom event object
var evt = $.Event("select2-selecting", {
val: data.id,
data: data
});
// Add the project to the list
$("[name=projects]")
.select2("data", [data])
.trigger(evt);
});
这应该为您复制原始的
select2 selection
事件,并允许您重用事件处理程序。当您像在第二个代码段中那样执行时,事件是否确实会触发?它将其添加到select字段中,并且显示得很好。但是,没有数据随它一起传递,因此e
的警报/控制台总是未定义的。据我记忆,您的数据不是直接在事件对象上访问的,而是在e.data propertyStrange中访问的,当我执行console.log(e)时
数据属性表示未定义。但无论如何,事件都不应该是未定义的。非常感谢!正是我需要的:)