开发者

Javascript in chrome plugin has syntax error

chrome.tabs.executeScript(null, {code:"$.each(selectValues, function(key='" + timestamp + "', value='Custom')
{   
     $('#expire').
          append($(\"<option></option>\").
 开发者_如何学JAVA         attr(\"value\",key).
          text(value)); 
});"});

It says that the first line has a syntax error, and the WebKit inspector shows odd highlighting patterns.

What's wrong with that? A friend thinks I need to escape some characters somewhere.

Thanks for the help!


That's definitely not valid syntax. You have an equal sign in the formal parameter list.

It will presumably end up as:

$.each(selectValues, function(key='someTime', value='Custom')
{   
     $('#expire').
          append($(\"<option></option>\").
          attr(\"value\",key).
          text(value)); 
});

I recommend you use the file option if possible, so you don't have to deal with escaping issues:

chrome.tabs.executeScript(null, {file: "myScript.js"});

The presumably the code in myScript.js will be something like:

$.each(selectValues, function(key, value)
{   
     $('#expire').
          append($("<option></option>").
          attr("value",key).
          text(value)); 
});

However, it's not clear what you're trying to do. jQuery.each takes a callback with two parameters, but what do you expect to happen to the values on the right of the equal sign?


You cannot use each that way. $.each() expects a function as callback that expects two parameters: index and value.

jQuery.each( collection, callback(indexInArray, valueOfElement) )

You cannot pass your own data to a function definition.

This is not related to jQuery, but to JavaScript in general.

If you use each, the parameters that get passed to the function come from the collection. You cannot pass custom parameters.

What do you want to do? If you want to set #expire just do it without each:

$("<option></option>").val('Custom').text(timestamp).appendTo('#expire');

If you are unfamiliar with jQuery, then read a tutorial.


In other languages like PHP and Python it means that you provide a default value to the parameters. However this is not possible in JavaScript (in this way).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜