Javascript/jQuery(无法按我希望的方式工作):
function chkKey(event) {
if (event.keyCode == 13) {
$(this).val("value", "wow such code");
};
};
我不想按名称引用文本字段,因为我将在页面上有多个使用相同 chkKey 函数的不同名称的文本字段。无论名称如何,我都需要引用我当前所在的文本字段。这可能吗?我认为这是一个 parent /冒泡问题,但我根本没有这些事情的经验。
编辑:完整的 HTML/JS:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Boxes and Lines</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div id="outerDiv">
<input type="button" name="btnNewField" value="Add New Field" onclick="appendNewField()">
<p></p>
<div id="mainDiv"></div>
</div>
<script>
function chkKey(event) {
if (event.keyCode == 13) {
$(this).val("value", "wow");
};
};
// returns a text field object
function txtField(fieldName, fieldVal){
var objTxtField = document.createElement("input");
$(objTxtField).attr({
type: "text",
name: fieldName,
value: fieldVal,
onkeyup: "chkKey(event)"
});
return objTxtField;
};
// if there is no appended text field, create one and give it focus
function appendNewField() {
if ($("#mainDiv").find('[name="appTxtField"]').length === 0 ) {
$(new txtField("appTxtField", "")).appendTo($("#mainDiv")).focus();
};
};
</script>
</body>
</html>
最佳答案
您的代码中有两个错误:
- 像使用
attr
或prop
一样使用val
,但它只需要一个参数 - 尝试使用
attr
添加一个keyup
事件处理程序,您应该使用on
看看下面的代码,用上面的项目修复:
function chkKey(event) {
if (event.keyCode == 13) {
$(this).val("wow such code");
};
};
// returns a text field object
function txtField(fieldName, fieldVal){
var objTxtField = document.createElement("input");
$(objTxtField).attr({
type: "text",
name: fieldName,
value: fieldVal
}).on('keyup', chkKey);
return objTxtField;
};
// if there is no appended text field, create one and give it focus
function appendNewField() {
if ($("#mainDiv").find('[name="appTxtField"]').length === 0 ) {
$(new txtField("appTxtField", "")).appendTo($("#mainDiv")).focus();
};
};
appendNewField()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mainDiv"></div>
关于javascript - 引用我按回车键时所在的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857347/