将数据传递给onclick事件会使字符串大写

时间:2018-07-03 02:17:55

标签: javascript jquery html

考虑这个小提琴:

var test = $('#test');
var click = $('#click');
var data = [{
  id: "gDDWdwewqeWEDQWE222wedEDDEW"
}, {
  id: "232exEWXDWE23e21EDXXE!!@q"
}];

click.click(function() {
  var data = [{
    id: "gDDWdwewqeWEDQWE222wedEDDEW"
  }, {
    id: "232exEWXDWE23e21EDXXE!!@q"
  }];
  var html = '';
  for (var i = 0; i < data.length; i++) {
    var id = data[i].id;
    html += `<li id="${id}" onclick="anyFunction("${id}")">${id}</li>`
  }
  test.html(html);
  console.log(test.html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>
<button id="click">Click me</button>

单击“单击我”,然后右键单击ID并检查它,您将在onclick事件外看到预期的ID,而其中的一个意外事件(去大写)在onclick事件中,在onclick内传递的ID之前还有空格事件。查看下面的图片。

enter image description here

是否知道为什么会发生这种行为?是错误还是我做错了什么?

1 个答案:

答案 0 :(得分:3)

由于您的HTML字符串未正确转义,因此它似乎已被转换为小写-jQuery的html()会将属性和元素名称转换为小写:

$('body').html('<FOO BAR="BAZ"></FOO>');
console.log($('body').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

要解决此问题,请将anyFunction的字符串参数改为单引号而不是双引号:

var test = $('#test');
var click = $('#click');
var data = [{
  id: "gDDWdwewqeWEDQWE222wedEDDEW"
}, {
  id: "232exEWXDWE23e21EDXXE!!@q"
}];

click.click(function() {
  var data = [{
    id: "gDDWdwewqeWEDQWE222wedEDDEW"
  }, {
    id: "232exEWXDWE23e21EDXXE!!@q"
  }];
  var html = '';
  for (var i = 0; i < data.length; i++) {
    var id = data[i].id;
    html += `<li id="${id}" onclick="anyFunction('${id}')">${id}</li>`
  }
  test.html(html);
  console.log(test.html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>
<button id="click">Click me</button>

但是内联处理程序是一种糟糕的做法-最好使用Javascript正确附加侦听器,这不仅是更好的设计方式,而且还使您不必担心像这样的字符串转义:

var test = $('#test');
var click = $('#click');
var data = [{
  id: "gDDWdwewqeWEDQWE222wedEDDEW"
}, {
  id: "232exEWXDWE23e21EDXXE!!@q"
}];

click.click(function() {
  var data = [{
    id: "gDDWdwewqeWEDQWE222wedEDDEW"
  }, {
    id: "232exEWXDWE23e21EDXXE!!@q"
  }];
  var html = '';
  for (var i = 0; i < data.length; i++) {
    const id = data[i].id;
    const li = $(`<li id="${id}">${id}</li>`);
    li.on('click', () => anyFunction(id));
    test.append(li);
  }
  console.log(test.html());
})
function anyFunction(arg) {
  console.log(arg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>
<button id="click">Click me</button>