Uncaught SyntaxError: 意外的令牌 ‘-‘

huangapple go评论86阅读模式
英文:

Uncaught SyntaxError: Unexpected token '-'

问题

<script type="text/javascript">
    jQuery('.mit div')
        .attr({"data-slick": '{"slidesToShow": 3, "slidesToScroll": 1}' });
</script>

需要在使用 slick slide 时得到以下结果:

<div data-slick='{"slidesToShow": 4, "slidesToScroll": 4}'>
英文:

I'm trying to add some attribute to an element with some jQuery, but I'm getting a syntax error Uncaught SyntaxError: Unexpected token '-'

&lt;script type=&quot;text/javascript&quot;&gt;
		  jQuery(&#39;.mit div&#39;)
           .attr({data-slick:&#39;{&quot;slidesToShow&quot;: 3, &quot;slidesToScroll&quot;: 1}&#39;
		  });
&lt;/script&gt;

I need to have a result as this below when working with slick slide.

&lt;div data-slick=&#39;{&quot;slidesToShow&quot;: 4, &quot;slidesToScroll&quot;: 4}&#39;&gt;

答案1

得分: 7

你不能在JavaScript对象键中使用-。如果需要使用-,则必须使用&quot;&#39;进行转义:

jQuery('.mit div')
  .attr({'data-slick':'{"slidesToShow": 3, "slidesToScroll": 1}'});
英文:

You can't have a - in a JavaScript object key. If you need one, then you have to escape it with &quot; or &#39;:

jQuery(&#39;.mit div&#39;)
  .attr({&#39;data-slick&#39;:&#39;{&quot;slidesToShow&quot;: 3, &quot;slidesToScroll&quot;: 1}&#39;
});

huangapple
  • 本文由 发表于 2020年1月3日 20:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定