簡體   English   中英

jQuery-如何從同一個類中的隱藏輸入ID中獲得不同的值?

[英]jQuery - how to get different value from hidden input id inside same class?

我想從同一個類中的隱藏輸入ID中獲得不同的值。 這是我嘗試創建的html和jQuery的一些示例代碼。

 <li>
   <div class="test"><img src="course.png"/><p class="text">Computer</p>
    <span class="list">
      <p>Course 1 <input type="hidden" id="id1" value="1"></p>
      <p>Course 2 <input type="hidden" id="id2" value="2"></p>
      <p>Course 3 <input type="hidden" id="id3" value="3"></p>
    </span> 
   </div>
  </li>

我正在嘗試創建的代碼

$(".test p").click(function(){
    var id= $(this).find('#id1').val(); 
    var id= $(this).find('#id2').val();
    var id= $(this).find('#id3').val();
    alert(id);    // will return value 1 or 2 or 3 if click on any course
});

不要使用“ id”作為變量名。

這應該工作:

$(".test p").click(function(){
    var myID = $(this).find('input').val(); 
    alert(myID);    // will return value 1 or 2 or 3 if click on any course
});

jsFiddle演示

最好為p和input標簽設置類,而不要使用id

 <li>
   <div class="test"><img src="course.png"/><p class="text">Computer</p>
    <span class="list">
      <p class="myCourse">Course 1 <input type="hidden" class="myCourseVal" value="1"></p>
      <p class="myCourse">Course 2 <input type="hidden" class="myCourseVal" value="2"></p>
      <p class="myCourse">Course 3 <input type="hidden" class="myCourseVal" value="3"></p>
    </span> 
   </div>
  </li>

$(".test .myCourse").click(function(){
    var myValue = $(this).find('.myCourseVal').val()); 
    alert(myValue);
});

最好使用class而不是input tag ,因此,如果將來添加其他輸入,則可以根據需要正確獲取值。

如果你不使用類,你的願望p如果你點擊S上Computer代碼將開始運行。

如果要獲得課程名稱中包含的課程值,請執行以下操作:

$(".test .text").click(function(){
   var x = [];
   foreach('.myCourse',function(){
       x.push($(this).find('.myCourseVal').val(); 
   })
   alert(x);
});

暫無
暫無

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

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