首页 > 解决方案 > 从自定义 html 结果中获取数据属性

问题描述

假设我有一个简单的 DALautocompleteform呈现自定义 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

标签: django-autocomplete-light

解决方案


好的,在挖掘了更多之后,我找到了两个解决方案,我将在这里粘贴,以防其他人遇到同样的问题。

所以这里的问题是$(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

推荐阅读