Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

如何通过按钮获取当前值?

我是想通过button点击后,获取当前的input的value值:

<table class="table table-light">
<tbody>
<tr>
<td> 
<input type="hidden" name="ids" value="1">
<button type="button" id="post" >确认</button>
</td>
<td> 
<input type="hidden" name="ids" value="2">
<button type="button" id="post"  >确认</button>
</td>
<td> 
<input type="hidden" name="ids" value="3">
<button type="button" id="post"  >确认</button>
</td>
<td> 
<input type="hidden" name="ids" value="4">
<button type="button" id="post">确认</button>
</td>
</tr>
</tbody>
</table>

第2或第3个按钮点击总是获取第一个值,取不到第2 3个

$("button[id=post]").on('click',function(){
  console.log($("input[type='hidden']").attr("value"))
})
      

有什么办法吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

id要具有唯一性。

<table class="table table-light">
    <tbody>
        <tr>
        <td> 
            <input type="hidden" name="ids1" value="1">
            <button type="button" class="js_confirm_btn_1" data-input-name="ids1">确认</button>
        </td>
        <td> 
            <input type="hidden" name="ids2" value="2">
            <button type="button" class="js_confirm_btn_3" data-input-name="ids2">确认</button>
        </td>
        <td> 
            <input type="hidden" name="ids3" value="3">
            <button type="button" class="js_confirm_btn_3" data-input-name="ids3">确认</button>
        </td>
        <td> 
            <input type="hidden" name="ids4" value="4">
            <button type="button" class="js_confirm_btn_4" data-input-name="ids4">确认</button>
        </td>
        </tr>
    </tbody>
</table>
$('button[class^="js_confirm_btn_"').on('click', function(e){
  console.log($("input[name='"+ $(e.currentTarget).data('input-name') + "']").val())
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...