0

我正在尝试拆分我要传入的字符串

$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" +  "<br />");

似乎将错误传递给我

SyntaxError: syntax error

splitName(

不知道这是怎么回事......如果有帮助,这里是 splitname 函数

function splitName(txt){
    var myString = txt;

    var mySplitResult = myString.split(" ");

    console.log("The first element is " + mySplitResult[0]); 
    console.log("<br /> The second element is  " + mySplitResult[1]); 
    console.log("<br /> The third element is  " + mySplitResult[2]); 

};
4

2 回答 2

2

当您将引号放在引号中并尝试正确转义时,很难做到正确。你理解错了。

一个解决方案是将其分成小部分:

var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">..."); 

但最好的解决方案是遵循最佳实践,即不是内联 javascript,而是使用 jQuery 的绑定函数:

$("#groupUL").append("... <a id=myid ..."); 
$("#myid").click(function(){ splitName(response.data[i].from.name) });
于 2013-03-21T22:47:49.133 回答
0

我认为您的代码的唯一问题是您的可读性问题。所以我建议请改进它。让我们来看看它。我的代码示例@JSbin。

这是代码:-(我认为更好)

var response = {
  data : {
    message: 'Cleaning code',
    from: {
      name: 'Clean Code works'
    }
  }
};


var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)

$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
  .html(response.data.from.name)
  .appendTo(li)
  .click(function() {
    splitName(response.data.from.name);
  });

$('<br>').appendTo(li);

// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');

function splitName(txt){
    var myString = txt;

    var mySplitResult = myString.split(" ");

    console.log("The first element is " + mySplitResult[0]); 
    console.log("The second element is  " + mySplitResult[1]); 
    console.log("The third element is  " + mySplitResult[2]); 
}
于 2013-03-22T13:45:25.557 回答