我有两个<select>元素,并且两个初始化都是相同的。

但是它们的ids是不同的,我想在初始化内访问它们的id属性。

<select name="names[]" id="user_name" class="tags required_field" style="width: 150px;">
    <option>Rakesh Malakar</option>
    <option>John Wick</option>
</select>
<script type="text/javascript">
<select name="emails[]" id="user_email" class="tags required_field" style="width: 200px;">
    <option>malakar_rakesh@gmail.com</option>
    <option>johnwich@yahoo.com</option>
</select>

$(".tags").select2({
    tags: true,
    placeholder: event.target.id == 'user_name' ? 'Select Name' : 'Select Email', // something like this
    language: {
        noResults: function() {
            return 'Type and enter to add new';
        },
    },
    escapeMarkup: function(markup) {
        return markup;
    },
});
</script>

最佳答案

这样的事情应该工作:

$(".tags").each(function() {
  var placeholder = "Select Email";
  if ($(this).attr('id') === 'user_name') {
    placeholder = "Select Name";
  }
  $(this).select2({
    tags: true,
    placeholder: placeholder
    language: {
      noResults: function() {
        return 'Type and enter to add new';
      },
    },
    escapeMarkup: function(markup) {
      return markup;
    },
  });
});

07-24 17:22
查看更多