[英]html - <input type=button> and <button>
I'm trying to get a button value in my textarea which is working fine if I use <button>
but if I use <input type=button>
then it not works. 我正在尝试在我的文本区域中获取按钮值,如果我使用<button>
可以正常工作,但是如果我使用<input type=button>
则它不起作用。 Could you find out what is the problem? 您能找出问题所在吗?
HTML 的HTML
<textarea id="txt-area" readonly></textarea>
<button class="buttons">1</button>
<button class="buttons">2</button>
<button class="buttons">3</button>
<button class="buttons">4</button>
<input type="button" class="buttons" value=" Test">
JavaScript 的JavaScript
$(document).ready(function () {
$(".buttons").click(function () {
var cntrl = $(this).html();
$("#txt-area").val(function (_, val) {
return val + cntrl + ","
});
});
});
For you have to get value but not innerHTML. 因为您必须获得价值,但不能获得innerHTML。 So in your code it should be 所以在你的代码中
var cntrl = $(this).html() || $(this).val();
<textarea id="txt-area" readonly></textarea>
<button class="buttons">1</button>
<button class="buttons">2</button>
<button class="buttons">3</button>
<button class="buttons">4</button>
<input type="button" class="buttons" value=" Test">
$(document).ready(function () {
$(".buttons").click(function () {
var cntrl = $(this).html();
$("#txt-area").val(function (_, val) {
return val + cntrl + ","
});
});
});
this the above code you have posted in jsfiddle... 这是您在jsfiddle中发布的上述代码...
if you use means you are giving values 如果您使用意味着您正在提供价值
Inseated of this var cntrl = $(this).html();
插入了此var cntrl = $(this).html();
Use var cntrl = $(this).val();
使用var cntrl = $(this).val();
working version has been updated below link 工作版本已在下面的链接中更新
BUTTONs have innerHTML but INPUTs don't. 按钮具有innerHTML,而INPUT没有。 You need to check if the element's tag name is Input or Button 您需要检查元素的标签名称是Input还是Button
Check this updated fiddle 检查此更新的小提琴
$(document).ready(function () {
$(".buttons").click(function () {
var cntrl = $(this).html();
if ($(this)[0].nodeName == "INPUT" )
{
cntrl = $(this).attr( "value" );
}
$("#txt-area").val(function (_, val) {
return val + cntrl + ","
});
});
});
If you are using [<button>]
, then you should use $('.class').text();
如果使用[<button>]
,则应使用$('.class').text();
In case you are using [<input type="button">]
, then $('.class').val();
如果您使用[<input type="button">]
,则使用$('.class').val();
would work fine. 会很好的。
$(document).ready(function () { $(".buttons").click(function () { var cntrl = $(this).html() || $(this).val();; $("#txt-area").val(function (_, val) { return val + cntrl + "," }); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <textarea id="txt-area" readonly></textarea> <button class="buttons">1</button> <button class="buttons">2</button> <button class="buttons">3</button> <button class="buttons">4</button> <input type="button" class="buttons" value="Test">
hope this help someone! 希望这对某人有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.