简体   繁体   English

Django admin - 自动完成选择不会发出“更改”事件

[英]Django admin - autocomplete select doesn't emit "change" event

I have a model, Color , with a foreign key mill that I'd like to autocomplete.我有一个模型Color ,我想自动完成一个外键mill Furthermore, I'd like to detect when the mill select box changes and do something with that in Javascript.此外,我想检测mill选择框何时发生变化并在 Javascript 中对其进行处理。 However, I can't seem to trigger any JS off the select box being changed.但是,我似乎无法从正在更改的选择框中触发任何 JS。

I set up my admin like so:我像这样设置我的管理员:

# admin.py

class MillAdmin(admin.ModelAdmin):
    search_fields = ['name']

class ColorAdmin(admin.ModelAdmin):
    class Media:
        js = ['js/jquery/jquery.min.js', 'js/admin/some-function.js',]

    autocomplete_fields = ['mill']

And I write some Javascript:我写了一些 Javascript:

// some-function.js

console.log('loaded script');
document.addEventListener('change', (function(e) {
    console.log('detected change event somewhere')
}))
console.log('event listener added')

In my browser console, when I visit the Color page, I see:在我的浏览器控制台中,当我访问 Color 页面时,我看到:

loaded script
event listener added

But when I select a mill, nothing more is logged.但是当我选择一个工厂时,没有更多的记录。

Further notes :进一步说明
The autocomplete itself is working just fine -- I am able to choose the mill I want, save, etc. Furthermore, if I remove autocomplete_fields = ['mill'] from my admin, I see that the vanilla select box does trigger the change event as expected:自动完成本身工作得很好——我可以选择我想要的工厂,保存等。此外,如果我从我的管理员中删除autocomplete_fields = ['mill'] ,我看到香草选择框确实触发了change事件如预期:

loaded script
event listener added
detected change event somewhere

I dug around in the source code long enough to find that Django is using Select2 , which promises to emit the change event just as if it were a normal select box.我在源代码中挖掘了足够长的时间,发现 Django 正在使用Select2 ,它承诺发出更改事件,就像它是一个普通的选择框一样。 But if that is happening, something else in the page must be eating it, because I'm not seeing it.但如果发生这种情况,页面中的其他东西一定在吃它,因为我没有看到它。 What's going on?这是怎么回事? If there's a conflict between Django and Select2, does anyone know a workaround?如果 Django 和 Select2 之间存在冲突,有人知道解决方法吗? Thanks!谢谢!

Events triggered by jQuery cannot be observed by native event listeners.本机事件侦听器无法观察到 jQuery 触发的事件。 Select2 uses jQuery's trigger function to handle events, which doesn't fire native DOM events, but you can swap the jQuery trigger for a native DOM one as illustrated here https://github.com/select2/select2/issues/4686 Select2 使用 jQuery 的触发器函数来处理事件,它不会触发原生 DOM 事件,但您可以将 jQuery 触发器替换为原生 DOM 触发器,如下所示https://github.com/select2/select2/issues/4686

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM