簡體   English   中英

獲取被點擊的錨標簽的ID

[英]Getting the id of the anchor tag which was clicked

這是來自php數據庫的數據的列表表示形式。使用foreach php循環獲取列表,並相應地填充achor標記內的數據。

<?php foreach($array as $iterate):?>
 <div class="col-sm-3">
  <div class="panel panel-default">
   **<a onClick='theFunction();' id="hello" href="#myModal" style="text-decoration:none;">**
    <div class="panel-heading">
     <img src ="audi_sillhouete.jpg" style="height:100%; width:100%;">
       <p id="10" style="position:absolute; top:10%; padding-left:5%; padding-right:15%;"><?php echo $iterate->test_name ?></p>
    </div>
   </a>                    
  </div>
</div>
<?php endforeach;?>

正如您在此處看到的那樣,我已將錨標記內的href調整為一個模式框,該模式框將在用戶單擊任何鏈接時顯示一條消息。 模態窗口中有一個按鈕,它將帶用戶到其他頁面。 問題是我想將某些值與url一起傳遞,但是不能這樣做,因為到下一頁的鏈接是在模式窗口規范部分中定義的。 所以我想出了這個解決方案。 我想到了使用錨標記的id屬性,我試圖獲取使用javascript單擊的錨的id屬性。

<script type="text/javascript">
 function theFunction()
 {
    var id = $('a', this).attr('id');
    alert(id);
 }</script>

由此,我想初始化一個php變量,然后使用該php變量作為值傳遞給模態窗口按鈕的href。 但是由於某種原因,我在警報框中獲得的值是“未定義”。 我已經嘗試過所有可能的組合。

$('a',this).attr('id');
$this.id;

一切都返回“未定義”。

參考-這是模態窗口部分的代碼。

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Instructions</h4>
      </div>
      <div class="modal-body">
       Your test is about to commence. A timer will be initiated after the moment you start the test. You may choose to answer a question, or leave it empty. You can also attempt the questions in any order that you find suitable.<br><br>Upon completion of the test, click on "Submit" to see your performance statistics.<br><br><br>Good luck!
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <a href="../test/pretest.php?test=<?php echo $testname?>" style="text-decoration:none;color:white;"><button type="button" class="btn btn-primary">Continue</button></a>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

請嘗試這個

$(document).on('click', 'a', function () {
    alert(this.id);
});

DEMO

您可以在錨中使用其他屬性,例如:

<a href='' id='hello' para-id='somevalue'></a>

alert($("#hello").attr("para-id"));

下面的jQuery函數在頁面加載時貫穿所有a標簽,並將id添加到鏈接的末尾。

$(function(){
    $('a').each(function(){
        var id = $(this).attr('id');
        var url = $(this).attr('href') + '?id=' + id;
        $(this).attr('href',url);
        });
});

https://jsfiddle.net/yc1hswet/

暫無
暫無

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

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