简体   繁体   English

jQuery:如何使用FancySelect插件强制“选择”选项?

[英]JQuery: How to force a select option to be “selected”, using FancySelect plugin?

I have a direct question : How to make "selected" an option of a select using FancySelect plugin? 我有一个直接的问题 :如何使用FancySelect插件使“选择”成为选择的选项?

This is the situation : I have a select with two options and two links. 这是这种情况 :我有两个选项和两个链接的选择。 The links should be synchronized with the select. 链接应与选择同步。 That means that when clicking on a link, it must make "selected" an option of the select. 这意味着,单击链接时,它必须使“已选择”成为选择的选项。

It is important notice anyway that it is not a normal select, but i am using a JQuery plugin called FancySelect : http://code.octopuscreative.com/fancyselect/ And this can be the main reason why normal solutions found elsewhere in StackOverflow did not apply to my specific case. 无论如何,重要的是注意这不是正常的选择,但是我正在使用一个名为FancySelect的JQuery插件: http : //code.octopuscreative.com/fancyselect/这可能是在StackOverflow的其他地方找到正常解决方案的主要原因不适用于我的具体情况。 So the point is not how to make "selected" an option of a select, but how to make it "selected" while using the FancySelect plugin. 因此,重点不在于如何使“选择”成为选择的选项,而是如何在使用FancySelect插件时使其“被选择”。

Here you can understand better: 在这里您可以更好地了解:

http://jsbin.com/AqoYucAG/11/edit http://jsbin.com/AqoYucAG/11/edit

This is the code i am trying to use, but is not working yet: 这是我尝试使用的代码 ,但尚无法正常工作:

$( "#a1" ).click(function() {

     $("#selector option:first").attr('selected','selected');
 });

Can you tell me please how can i force an option of a select to be "selected"? 您能告诉我如何强制选择一个选项吗? Thank you very much! 非常感谢你!

It seems like you are using a select plugin. 似乎您正在使用选择插件。 So generally they convert the underlying select to divs/spans etc to achieve good look and feel. 因此,通常它们会将基础select转换为div / span等,以获得良好的外观。 And hence when you change the select option you need to notify the plugin saying that you have updated it. 因此,当您更改选择选项时,您需要通知插件说您已更新它。 In this case it seems like you can trigger a change/update event to do so. 在这种情况下,您似乎可以触发change/update事件。 You need to do the same thing (triggering an update ) when you add options dynamically to the select as well, so that the plugin gets updated. 在向select中动态添加选项时,您需要做同样的事情(触发update ),以便插件得到更新。

So try: 因此,请尝试:

$( "#a1" ).click(function(e) {
   e.preventDefault();
   $("#selector").val("1").trigger('change');
});

According to the plugin code as shown below, it updates the text while change is triggered. 根据如下所示的插件代码,它会在触发更改时更新文本。

sel.on('change', function(e) {
    if (e.originalEvent && e.originalEvent.isTrusted) {
      return e.stopPropagation();
    } else {
      return updateTriggerText();
    }
  });

最简单的方法,您不需要任何选项标签

 $("#selector").val("myVal");

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

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