简体   繁体   中英

Jquery on off first click doesn't fire on first click

I'm using MVC 5 and Razor front end. When I click any button for the first time, it will not play. It will play on the second click. I tried .off at the end of the code but it didnt work. I want it to play for the first click on a button then turn off. Right now it takes two clicks on a button to start the track and work correctly for the other tracks.

function play() {
//$(".song").unbind().click(function () {
$(".song").off('click').on('click', function () {

        //this is the url
        var url = $(this).attr("data-song");

    var audio = $("#myAudio")[0];

    if (audio.paused) {
        audio.src = url;
        audio.play();
    } else {
        audio.pause();
        audio.currentTime = 0;
    }


});

Here is my HTML:

<table class="table" id="trackTable">
<tr>
    <th>

    </th>
    <th>
        @Html.DisplayNameFor(model => model.Title)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Genre)
    </th>

</tr>

@foreach (var item in Model)
{
    <tr>
        <td class="songRow">
            <a href="#"  class="song" data-song="@Url.Content(item.Path)"  onclick="play()" ><img src="~/Images/playpause.png" alt="playpause" id="playbutton"   /></a>

        </td>

        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Genre)
        </td>
        <td></td>
    </tr>
}

Have you tried this?

$(".song").on('click', function () {
   $(this).off('click');

   // do the other stuff
}

This way your link can be clicked once, and then click event handler is removed.

在此,您首先使用点击功能,而不是使用关闭点击

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