【问题标题】:Get current array of hidden html element value on the click of array of buttons单击按钮数组获取当前隐藏的html元素值数组
【发布时间】:2016-06-12 15:11:01
【问题描述】:

我有html元素:

<input type=hidden class=txtCustomerId value=".parent::current()." />";
<input type=button class=printToTextarea value='Get to box' />

和jquery:

$(".printToTextarea").on("click", function () {
    var array = $('.txtCustomerId').map(function() {
    return this.value;
}).get();
     loadxmldoc(array);
 });

它将所有元素作为类名txtCustomerId 的隐藏字段作为数组传递,而单击按钮时我只需要当前元素。按钮也是数组,两者应该有相同的索引。

【问题讨论】:

  • 这是实际的代码布局吗?答案大不相同
  • 使用this获取被点击的元素
  • @then 我需要在按钮单击后的另一个元素值

标签: javascript jquery arrays html dom


【解决方案1】:

以下代码使用eq()index()在很大程度上满足要求。

$(".printToTextarea").on("click", function () {
    var i = $('.printToTextarea').index(this);

    var custid=$('.txtCustomerId').eq(i).val();

     loadxmldoc(custid);
    $("#textInput").focus();
 });

【讨论】:

    【解决方案2】:

    变化:

    $('.txtCustomerId')
    

    到:

    $(this).prev('.txtCustomerId')
    

    【讨论】:

    • $(this).prev('.txtCustomerId').val() 在警报中显示未定义
    • 如果我们从 printToTextarea 字段中获取值,我认为可以使用 $(this)
    • 我看不到结果
    • 您是否打开了浏览器的控制台?您应该使用控制台进行调试,而不是警报。
    【解决方案3】:

    你选择了所有的元素。所以你需要选择一个相关的。在您的示例中,您将使用 prev() 来获取对元素的引用。

    $(".printToTextarea").on("click", function () {
        var button = $(this);
        var inputValue = button.prev(".txtCustomerId").val();
        console.log(inputValue);
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type=hidden class=txtCustomerId value="hello" />
    <input type=button class=printToTextarea value='Get to box' />

    但是如何获取输入实际上取决于您的 HTML。因此,如果结构与彼此相邻的两个元素不同,那么选择它的方式就会改变。

    【讨论】:

    • 按钮和隐藏元素都是数组,所以我想在按钮点击相同索引时获取隐藏元素值。
    • 比使用 index() 和 eq(),但似乎脱离 HTML 结构会有意义...
    • 是的,我已经使用相同的功能并在下面发布答案,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2019-02-15
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多