簡體   English   中英

Javascript/Jquery onClick 使用 HTML Div 不起作用

[英]Javascript/Jquery onClick using HTML Div not working

當我單擊“php1”div 時,它什么也不做。

location.reload() 是一個占位符,只是一種了解 onClick 是否有效的簡單方法。

    <div class="php-task">
      <h1>PHP</h1>
      <div id="php1" class="text">
        <p>Display/setvars</p>
      </div>
    </div>
    $("#php1").click(function (e) { 
      e.preventDefault();
    
      $.ajax({
        type: "POST",
        url: "php/pagehandler.php",
        data: {page: "task",task: 1},
        success: function (response) {
          location.reload();
        }
      }); 
    });

你可以試試下面的代碼嗎? 可能是您的 HTML 在頁面加載后動態加載。

$(function(){

    $('body').on('click', '#php1', function(e){
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "php/pagehandler.php",
        data: {page: "task",task: 1},
        success: function (response) {
          location.reload();
        }
      }); 

    });

});

只是為了向您展示它不適用於重復的 id 元素(並且它確實可以作為具有該id的第一個 div 的簡化示例,該id必須是唯一的):

 $("#php1").click(function (e) { console.log('clicked'); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="php-task"> <h1>PHP</h1> <div id="php1" class="text"><!-- clicking this will trigger the handler --> <p>Display/setvars</p> <p>clicking this will trigger the handler</p> </div> </div> <div class="php-task"> <h1>PHP</h1> <div id="php1" class="text"><!-- clicking this will NOT trigger the handler --> <p>Display/setvars</p> <p>clicking this will NOT trigger the handler</p> </div> </div>

我認為在你有多個 div php1,php2,php3...最好使用類來附加點擊事件:

 $(function() { $(".php-task .text").click(function(e) { e.preventDefault(); console.log('Task with id : ' + this.id + ' clicked.'); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="php-task"> <h1>PHP</h1> <div id="php1" class="text"> <p>Display/setvars</p> </div> </div> <div class="php-task"> <h1>PHP</h1> <div id="php2" class="text"> <p>Display/setvars</p> </div> </div> <div class="php-task"> <h1>PHP</h1> <div id="php3" class="text"> <p>Display/setvars</p> </div> </div><br><br><br>

$(document).ready(function () {
    $("#task").click(function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "php/pagehandler.php",
            data: {
                page: "task"
            },
            success: function (response) {
                location.reload();
            }
        });
    });

});

添加以下內容即可解決問題:

$(document).ready(function()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM