问题
I figure i've just been staring at my screen too long today - I can't find the error here. I've got a jQuery template and i'm using KnockoutJS's foreach on it. Inside i have a button and i'm trying to call a function onclick and pass in an iteration value. Here's the snippet from the template. The only thing that i can think would be wrong is something about my jQuery template syntax, tho it's working elsewhere
<button onclick="newTabify(${$data})">Chat</button>
My template looks like this...(the button's inside, along with a bunch of other stuff)
<div data-bind='template: {name: "contactTemplate", foreach:contacts}' id="contactList"></div>
<script id='contactTemplate' type='text/html'>
...
</script>
The newTabify function looks like:
function newTabify(contact) {
tabify($.inArray(contact, viewModel.contacts()));
}
What's extremeley odd here is the error.
SCRIPT1007: Expected ']'
default.html, line 1 character 19
Line 1 is my <head>
tag!!
If you need anymore markup just lemme know. Thanks!
EDIT: Here's my contact template. The funny thing is there's not a thing wrong with any of it except for the click event on the button when i try to add the line as shown above. But here's the rest anyways.
{{if $data.jid() != viewModel.jid() }}
<div class="wrapper" onclick="wrapperClick(this)">
<div style="padding-bottom:4px">
<img src=images/${$data.avail}.png> ${ $data.name } <img class="avatar" src=images/${$data.img}><br> <span class="status">${$data.status }</span>
</div>
<a href="mailto:${$data.jid}" >${$data.jid}</a> | <button onclick="newTabify(${$data})">Chat</button> | <button onclick="event.stopPropagation();">Call</button>
</div>
{{/if}}
EDIT 2: $data a contact object; i'm looping through contacts (an observable array of contact objects) and sucessfully pulling all the values out of contact, etc. Here's my contact:
function contact(name, status, avail, jid, img, convIndex){
return {
name : ko.observable(name),
status : ko.observable(status),
avail : ko.observable(avail),
img : ko.observable(img),
jid : ko.observable(jid),
convIndex: ko.observable(convIndex)
};
}
So technically $data should be a instanct of the above.
回答1:
I can't guarantee that this is your only problem, but this line is not going to give you what you are expecting:
<button onclick="newTabify(${$data})">Chat</button>
Doing ${$data} is going to give you the .toString() of your object. For your object it will look like:
[object Object]
So, this would not be valid syntax.
Since, you are using Knockout you can instead do something like this (even inside of a template) and it will pass the actual object properly:
<button data-bind="click: function() { newTabify($data); }">Chat</button>
回答2:
I suggest you run JSLint against your code. It should point you in the right direction.
来源:https://stackoverflow.com/questions/5844913/javascript-expected