简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM