2

我是一个初学者和自我感兴趣的网络编码员。

我一直在测试、询问、重新测试、尝试、阅读 javaScript 中的不同功能解决方案到一个在线表格,<textarea>'s一旦我完成,该表格将包含大量内容。

我很好,目前的功能状态是基于几个 js 事件。示例代码将是(写得很有趣,所以在论坛中更容易阅读,实际代码显然是一行):

<textarea
    data-id="0"
    class="classOne classTwo"
    id="dataInput_0"
    name="xInput_row_1"
        onFocus="functionOne();"
        onBlur="functionTwo();"
        onKeyUp="functionThree();">
</textarea>

我构建并测试了所有专门用于id="dataInput_0"using的功能getElementById。例子:

var d = document.getElementById("dataInput_0");

所以我的问题是如何让函数触发其他"dataInput"id 的?

换句话说:

var d = document.getElementById('whichever dataInput that is active/focused');

谢谢!

4

2 回答 2

2

使用当前代码的最简单方法是执行以下操作:

onFocus="functionOne(this);"

...然后定义你的功能:

function functionOne(el) {
   // el is the element in question, used e.g.:
   alert(el.name);
}

onFocus=...浏览器中设置this有问题的元素,因此您可以将其作为参数传递给您的函数。然后,您的函数只需直接使用它,而不必通过getElementById().

但是既然你提到了 jQuery,你可以从你的 html 中删除内联onFocus和其他onXYZ处理程序,并在你的 JS 中按如下方式完成所有操作:

$("textarea").focus(function() {
   // here this is the element in question, e.g.:
   alert(this.value);
});

这为页面上的所有 textareas 定义了一个焦点处理程序 - 将其缩小到仅具有类 "classOne" do 的 textareas $("textarea.classOne")。函数内this指的是焦点元素。您可以使用.blur()andkeyup()方法为代码中显示的其他事件分配处理程序。

于 2013-04-21T04:53:33.573 回答
0

我的建议是为此使用属性选择器$('input[id^="dataInput_"]')并以这种方式使用 jQuery 的.on()处理程序:

$('input[id^="dataInput_"]').on({
    focus: function{
       functionOne($(this));
    },
    blur:  function(){
       functionTwo($(this));
    },
    keyup: function(){
       functionThree($(this));
    }
});

和功能:

functionOne(obj){
   console.log(obj.val());
}
functionTwo(obj){
   console.log(obj.val());
}
functionThree(obj){
   console.log(obj.val());
}
于 2013-04-21T05:22:34.347 回答