Pergunta

<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>

<script>
    function playController(dataObj){
        alert(dataObj);
    }

    function playHandlers(){
        var dataObj = "stef";
        $('.audiocontrol').on('click', playController(dataObj));
    }

    $(document).ready(playHandlers);
</script>

This bit of code is firing off on page load whether I click the object or not. Why?

Foi útil?

Solução

What you want is:

function playController(dataObj){
    alert(dataObj);
}

function playHandlers(){
    var dataObj = "stef";
    $('.audiocontrol').on('click', function() { playController(dataObj); } );
}

$(document).ready(playHandlers);

The way your code was written, it was calling playController when you were registering it in the .on call.

jsfiddle

Outras dicas

You're invoking the function therefore passing the result of playController. You can do something like this.

function playHandlers(){
    var dataObj = "stef";

    $('.audiocontrol').on('click', function() {
        playController(dataObj);
    });
}

This will work:
(demo here)

function playController(dataObj) {
    alert(dataObj);
}

function playHandlers() {
    var dataObj = "stef";
    $('.audiocontrol').on('click', function () {
    playController(dataObj)
   });
}
$(document).ready(playHandlers);

This will load your code when the page loaded and call the function playHandlers(). You were calling it directly because you forgot to add function(){} in the on/click call.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top