如何在 Javascript 或 J-Query 中动态访问用户输入的输入字段数据

How to dynamically access user-entered Input-field-data, in Javascript or J-Query

本文关键字:输入 用户 访问 数据 字段 动态 Javascript J-Query      更新时间:2023-09-26

救命!!.... 我无法动态访问用户输入到Input字段中的数据!

我是一名课程设计师,试图进行"匹配"活动(18 个问题与 18 个打乱的可能答案),其中答案选项被动态划掉,1 个,当它们被学生"用完"时,每当他在输入字段中输入该选择的字母(在本例中为"r")时。 以下是这 18 个匹配项中 1 个的 HTML:(提示:注意"id"属性)

.HTML

<input title="Question 18 - type 'R' into this input field" 
    class="questions" maxlength="1" id="18" onblur="My_Blur_Fx(this);">   
</input>
<span class="r_as_selected, choices" id="r">  <!--I use the first class ('r_as_selected') in the J-Query example below, and the 2nd class ('choices') in the Javascript example below.-->
    [Choice] R. (**All this span should soon be crossed-out.**) 
</span>

我想我可以通过"改变"事件来实现这一目标。 然而,我的Javascript和J-Query似乎都做不到,因为两者都不能动态访问用户的输入(PHP通常通过GET或POST访问的东西)。

J-查询

我的 J 查询尝试动态访问此用户输入的输入...

$("input").change(function(){
    $("input"[value="r"])
        .add('.r_as_selected')
            .eq(1).css({'color': 'red', 'text-decoration': 'line-through'})
});

。失败了,因为,虽然它可以划掉"#r"答案选择,但每当他们输入任何东西时,它也会把它划掉......因此,代码的[value='r']部分无法针对某人键入"r"的字段。

爪哇语

我的 Javascript 尝试动态访问此用户输入的输入...

<script> 
    function My_Blur_Fx(x) {
        var userInput = document.getElementById(x).value;      
        var userChoices = document.getElementsByClassName("choices").id;
        var i;
        for(i = 0; i < 18; i++)
                { if (userChoices[i].attributes[1].value == userInput) {
                        /*Note: "attributes[1] is my way of accessing the 2nd attribute in the HTML span above, which is 'id="r"'*/ 
                    userChoices[i].style.textDecoration = "line-through";};
                };
    }
</script>

。也失败了,因为"输入"是一个"元素",其"值"由 DOM 定义为"NULL",...所以上面的第 3 行给出了一个错误。任何其他可能相关的 DOM 修饰符也不能代替.value(即 .innerHTML/.nodeValue/.attributes ) 访问该用户输入的值。 因此,似乎无法动态访问"输入"元素。 ( 任何建议...J-Query、Javascript 还是其他?)

不能使用属性选择器来匹配用户输入,它仅匹配静态属性,而不匹配动态值。您可以使用.filter()搜索与选择器匹配且具有特定值的元素。

$("input").change(function() {
    $("input").filter(function() {
        return this.value == 'r';
    }).add(".r_as_selected")
        .eq(1).css({'color': 'red', 'text-decoration': 'line-through'});
});

您在MyBlurFx()中有几个问题。

  1. document.getElementById(x).value不起作用,因为x是元素,而不是它的 ID。你应该只使用x.value .
  2. document.getElementsByClassName("choices").id不起作用,因为getElementsByClassName()返回一个NodeList,而不是单个元素,所以它没有id属性。但是您不需要 ID,只需使用 document.getElementsByClassName("choices") ,因为 for 循环对元素进行操作,而不是对 ID 进行操作。

也许不止一个错误,但我看到你的代码$("input"[value="r"])$(undefined)一样。必须改用$('input[value=''r'']')