数据属性中的 ES6 连接

ES6 concatenation inside data attribute

我正在将旧代码重构为 ES6 以不使用 Jquery:

Target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

但是,我遇到了 lint 错误:

ERROR: Unexpected string concatenation. [prefer-template]

问题是,在数据属性选择器内部,无法识别模板。

const slice = this.hash.slice(1);
target = target.length ? target : $('[name="${slice}"]');

它会说

ERROR: 'slice' is assigned a value but never used.

如有任何帮助,我们将不胜感激。

您需要使用反引号而不是引号:https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

$(`[name="${slice}"]`)