django-autocomplete-light - 从自定义 html 结果中获取数据属性
问题描述
假设我有一个简单的 DALautocomplete
并form
呈现自定义 html 结果,其中结果包含数据属性。
from django.utils.html import format_html
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_result_label(self, item):
return format_html('<span data-url="{}">{}</span>', item.get_dashboard_url(), item.name)
class CountryForm(forms.Form):
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
widget=autocomplete.ModelSelect2(
url="country-autocomplete",
attrs={
"data-result-html": True,
},
),
)
现在在选择时,我想获取所选项目的数据属性。
$(document).ready(function() {
$('#id_country').on('select2:select', function(e) {
// get the selected item data attributes.
});
});
我试过了$(this).find(":selected").data('url')
。但它返回undefined
解决方案
好的,在挖掘了更多之后,我找到了两个解决方案,我将在这里粘贴,以防其他人遇到同样的问题。
所以这里的问题是$(this).find(":selected")
返回option
但它没有数据属性,因为所有的html都在它的text
属性内($(this).find(":selected").text()
返回标记。);
解决方案 1
所以第一个解决方案是执行以下操作(我不确定 jQuery 在幕后做了什么,它可能会解析标记并从中创建一个对象)。
$($(this).find(":selected").text()).data('url')
解决方案 2
我注意到的另一件事是$(this).find(":selected").data()
返回select2
从 ajax 调用获得的数据。所以我们可以改变我们的视图来返回更多的数据。
class CountryAutocomplete(autocomplete.Select2QuerySetView):
# ... get_result_label()
def get_results(self, context):
"""Return data for the 'results' key of the response."""
return [
{
"id": self.get_result_value(result),
"text": self.get_result_label(result),
"url": result.get_dashboard_url(),
"selected_text": self.get_selected_result_label(result),
}
for result in context["object_list"]
]
现在在 Javascript 中我们可以使用:
$(this).find(":selected").data().data.url
推荐阅读
- c# - 如何让我的删除方法接受空值?
- sql - 如何在 SQL 中有条件地用另一个日期替换一个日期?
- c++ - 为什么访问模板化变体作为返回值抛出异常
- ios - 为什么 iOS 13 放弃了我的布局约束更改?
- version-control - 为什么我不能将代码推送到这个 Gitlab 项目?
- c# - 文本和文件名之间的相似性。需要更不精确
- c# - C#,MessageBox.Show 背后的机制
- python - Python 匹配元素相同但美元在 % 以内的记录
- python - 我们应该如何通过python循环中的索引引用它们的标记化名称来获取实际实例
- youtube - Youtube iframe API no-cookies GDPR 合规性