【问题标题】:What's wrong with my selector value?我的选择器值有什么问题?
【发布时间】:2018-02-10 17:29:45
【问题描述】:

我目前正在 Shopify 上为我的客户开发商店。他希望我添加一个功能,通过该功能可以跟踪用户的 IP 地址,并且他可以查看他自己特定国家/地区的货币。我正在使用以下代码: 我想将下拉列表中的选定值更改为“AUD” 我在这部分只得到一些语法错误:

jQuery("#select_selector option:selected").removeAttr("selected");

jQuery("#select_selector option:[value='"AUD"']").attr('selected', 'selected')

它说语法错误或缺少论据。

【问题讨论】:

  • 你必须像这样\"AUD\" 一样逃避你的"AUD"
  • 如果澳元是文本,则不需要引号,可以是[value=AUD]

标签: javascript jquery shopify selector


【解决方案1】:

您需要连接字符串和变量。您可以使用 + 运算符来执行此操作。 option之后也不需要冒号

jQuery("#select_selector option[selected]").removeAttr("selected");

jQuery("#select_selector option[value='" + AUD + "']").attr('selected', 'selected')

如果AUD 不是变量,那么您应该完全删除引号。

jQuery("#select_selector option[value=AUD]").attr('selected', 'selected')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_selector">
      <option value="ABC">ABC</option>
      <option value="123">123</option>
      <option value="AUD">AUD</option>
      <option value="EFG">EFG</option>
</select>

【讨论】:

  • 谢谢。我尝试运行相同的代码,但出现以下错误:-- n.fn.init [prevObject: n.fn.init(1), context: document, selector: "#select_selector option[value=AUD]" ]
  • 我也试过 value=\"AUD\" 但它对我不起作用
  • @AnchalVerma 肯定有其他问题,因为如果你运行上面的代码 sn-p 它可以正常工作。
【解决方案2】:

@Get Off My Lawn 的代码运行良好。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="select_selector">
      <option value="ABC">ABC</option>
      <option value="123">123</option>
      <option value="AUD">AUD</option>
      <option value="EFG">EFG</option>
</select>

<input type="button" value="click me" id="clickme">


<script>
 jQuery("#clickme").click(function(){
    jQuery("#select_selector option[selected]").removeAttr("selected");
    jQuery("#select_selector option[value=AUD]").attr('selected', 'selected');

});
</script>

或试试这个JSFiddle

最好将 AUD/USD 或任何货币作为变量。

【讨论】:

    【解决方案3】:

    option:[value='"AUD"'] 应该是 option[value=AUD]。不需要冒号。

    但实际上你可以使用

    jQuery("#select_selector").val('AUD');

    如果您使用来自https://help.shopify.com/themes/customization/currencies/show-multiple-currencies 的样本(我推荐) 那就是

    jQuery("#currencies").val('AUD');

    如果您是为首次访问者自动选择货币,您也应该尝试将货币选择存储在本地存储中。这不仅可以为您节省 geoip 查询,还可以让客户将该值覆盖为他们选择的货币。 Shopify 的示例在其代码中使用称为 cookieCurrency 的 cookie,因此您的 GeoIP 查找可以首先对其进行测试,并且仅在未设置时才进行查找。

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多