1.如何用jquery獲取<input id="test" name="test" type="text"/>中輸入的值?
方法一:
$("#test").val()
方法二:
$("input[name='test']").val()
方法三:
$("input[type='text']").val()
方法四:
$("input[type='text']").attr("value")
2.當 input type="hidden" 的值發生改變時,觸發自定事件,獲取改變后的值
demo_1.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery-1.8.2.js"></script> </head> <body> <input type="text" name="current" /> <input type="hidden" name="hidden" value="0"> <script> $("input[type='text']").on('input',function(){ var currentVal = $("input[type='text']").val(); // 觸發 改變 input type="hidden" 的值 $("input[type='hidden']").trigger('input:changed', currentVal); }) // 給 input type="hidden" 添加自定義事件 $("input[type='hidden']").on('input:changed', function (e, val) { // 獲取 input type="hidden" 的值 console.log(val); }); </script> </body> </html>
demo_2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery-1.8.2.js"></script> </head> <body> <input type="text" name="current" /> <input type="hidden" name="hidden" onpropertychange="changeVal()" value="0"> <script> $("input[type='text']").on('input',function(){ // 觸發綁定方法 changeVal(); }) // 給 input type="hidden" 添加 onpropertychange事件 function changeVal(){ // 獲取當前值 console.log($("input[type='hidden']").val()); // 0 } </script> </body> </html>
.