4

我有这个问题:

array[i].idAuthor 是一个字符串变量。我想将此字符串传递给在附加字符串中调用的函数。

除 Internet Explorer 外,该代码在 Chrome 和 Firefox 中运行良好。IE 给我这个错误: SCRIPT1014: Invalid character

我认为问题是`-Quotes

我希望以下示例有助于表达我的问题。

<script>
(...)
    $("#id").append("<div onClick='myFunc(`" + array[i].idAuthor + "`);'>" + i + "</div>");
(...)
<script>

是否有另一种方法来处理我的情况或将 `-Quotes 替换为与 IE 兼容的另一个字符?

4

3 回答 3

10

看起来您正在将反引号 (`) 放入您的字符串中。

onClick='myFunc(`" + ... + "`);'>

在现代浏览器中,反引号用于模板文字。IE11 不支持模板文字。

相反,请尝试转义您的引号:

onClick='myFunc(\"" + array[i].idAuthor + "\");'>
于 2016-05-19T19:32:48.610 回答
2

您应该使用普通引号,但要对它们进行转义,以便将它们作为字符串的一部分进行解析:

$("#id").append("<div onClick='myFunc(\"" + array[i].idAuthor + "\");'>" + i + "</div>");
//------------------------------------^^   ----------------------^^
于 2016-05-19T19:32:43.713 回答
1
//create element using jquery
var elm = $('<div>');

//put ID as custom attribute
elm.attr('data-author-id', array[i].idAuthor);

//put some html content for new element
elm.html(i);

// catch click on it
elm.click(function(){
    // call external function and pass your custom tag attribute as value
    myFunc( $(this).attr('data-author-id') );
});

    $("#id").append(elm);

类似的东西应该工作。

更多拍摄方式:

$("#id").append($('<div>')
.attr('data-author-id', array[i].idAuthor)
.html(i)
.click(function(){
    // call external function and pass your custom tag attribute as value
    myFunc( $(this).attr('data-author-id') );
}));

jQuery 有很多功能控制标签属性、事件、值和很多有用的东西。

于 2016-05-19T19:46:59.957 回答