javascript, curly brace in onclick dont work?
Solved, server side ate my {}.
I have this code in my HTML:
onclick="changes = {'a': 'b'};"
This transforms to
onclick="changes = ;"
when I load the page. So the curly braces and everything in between disappears. Any idea how to fix this? Ultimately, I开发者_C百科 want to give an anonymous object as input to a function:
onclick="dothis({'a': 'b', '1': '2'});"
What I would recommend is making your code more semantic, by having your inputs keep track of data, but the actual binding and execution separate:
<div id="myDiv" data-changes="{'a':'b', '1':'2'}"></div>
document.getElementById('myDiv').onclick = function() {
var data = JSON.parse(this.getAttribute('data-changes'));
// here you should be able to say data.a, data.1, etc.
};
Most modern browsers support native JSON methods:
Browser-native JSON support (window.JSON)
but for those that don't, you can add support with the JSON library:
https://github.com/douglascrockford/JSON-js
Have you considered/are you able to not use inline JavaScript? Just have an external JavaScript file that gets loaded with something like (not actual code, for example purposes):
getElementById("myButton").click( function(){
dothis({'a':'b','1':'2'})
})
Something like that (especially when paired with a library) can also save you from having to duplicate your code in every item you're looking to run that function in.
精彩评论