简体   繁体   中英

Changing function parameters onclick?

 <div class='unsubscribe'><a id='us$id' href='#' onclick='subscribe(u,$id);'>
<img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>

onclick how do i change the first parameter in the onclick function to 's'? So the next time it will look like this.

<div class='unsubscribe'><a id='us$id' href='#' onclick='subscribe(s,$id);'>
<img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>

I wouldn't do it like you want to. See the XY Problem .

Instead, what you should so, is keep track of the subscription state of the user, either using a cookie or an identifier on the link ( data-state="s" ), and take notes in the function.

Instead of setting onclick in your HTML do it with Javascript soon after. I'm assuming you're echoing all your code as a double quoted PHP string because of 'us$id' :

<div class='unsubscribe'>
    <a id='us$id' href='#'>
        <img src='/unsubscribe.jpg' alt='unsubscribe' />
    </a>
</div>
<script type='text/javascript'>
    document.getElementById('us$id').onclick = function(){
        // Subscribe u
        subscribe(u, $id);

        // Set all future clicks to subscribe s
        this.onclick = function(){
            subscribe(s, $id);
        };
    };
</script>

Instead of changing the string in the onclick , you can change it in the javascript itself. This is if you want to change all of the s to u throughout the page (wasn't sure if there was only one or if this is what your intention is).

Remove the first parameter:

<div class='unsubscribe'><a id='us$id' href='#' onclick='subscribe($id);'>
<img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>

Then change subscribe() to this:

function subscribe(id)
{
    // doing "static" variable in javascript
    if (typeof this.foo == 'undefined')
    {
        this.foo = 's';
    }
    else
    {
        this.foo = 'u';
    }

    ...
}

One way would be to change it textually; use var el = document.getElementById('us$id'); to retrieve the element, then search el.attributes for an attribute with .name value "onclick", and replace its child with a new TextNode with the second function call.

A different approach would be to change the HTML so that subscribe will get both u and s, and somehow (eg with a global variable, a static variable, etc.) remember if it's the first or second time that this method is invoked.

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