jQuery 检查隐藏元素并使用其数据

发布于 2024-11-30 18:25:29 字数 378 浏览 9 评论 0原文

我想在这里取得一些成就。单击链接后,为该链接指定的隐藏元素的值将设置为 1(默认为 0)。这很好用。

下一步,我将循环遍历所有隐藏元素以查看哪些元素设置为 1。如果设置为 1,我会将其 ID 添加到变量中。下一个被设置为1的,它的ID需要放在它后面的同一个变量中。

所以带有ID的变量应该看起来像:hidden1/hidden2/hidden3

这很难解释,但在这里我重建了它: http://jsfiddle.net/UgbMx/

一旦我单击“提交”按钮,它就会查找是否是1或0就好了。然后它循环遍历隐藏元素。它识别出该元素被设置为 1 或 0。之后,它就会出错。

I am trying to achieve something here. Once I click a link, the value of a hidden element specified for that link will be set to 1 (0 by default). This works fine.

Next step, I am looping through all hidden elements to see which ones are set to 1. If it is set to 1, I add its ID to a variable. The next one that is set to 1, its ID needs to be put in the same variable behind it.

So the variable with the IDs should look like: hidden1/hidden2/hidden3

It is hard to explain, but here I reconstructed it:
http://jsfiddle.net/UgbMx/

Once I click the the SUBMIT button, it looks up if it is 1 or 0 just fine. Then it loops through the hidden elements. It recongizes that the element is either set to 1 or 0. After that, it goes wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

铁憨憨 2024-12-07 18:25:29

删除回调中 test_total 之前的 var 语句,就可以了!您正在每个回调范围内重新声明 test_total 变量。

所以这部分被改变了(为了可读性我截断了评论):

            if (test_total == "EMPTY") {
                test_total = $(this).attr("id") + "/SEPERATOR/";
            // In case the variable [...]
            } else {
                test_total = test_total + $(this).attr("id") + "/SEPERATOR/";
            }

Remove the var statement before test_total inside the callbacks and you will be fine! You are re-declaring the test_total variable within the each-callback scope.

So this part is changed (I truncated the comment for readability):

            if (test_total == "EMPTY") {
                test_total = $(this).attr("id") + "/SEPERATOR/";
            // In case the variable [...]
            } else {
                test_total = test_total + $(this).attr("id") + "/SEPERATOR/";
            }
胡渣熟男 2024-12-07 18:25:29

您可以大大缩短您的解决方案:

test_total = $(".test_item[value='1']").map(function() {
    return this.id;
}).get().join("/separator/");

演示。

You can substantially shorten your solution:

test_total = $(".test_item[value='1']").map(function() {
    return this.id;
}).get().join("/separator/");

Demo.

情何以堪。 2024-12-07 18:25:29

您的问题在于您使用 var 声明新范围的范围,从而重置变量 test_total 请参阅 工作版本的更新小提琴

Your issue is with the scope you're using var to declare a new scope, thus resetting the variable test_total see the updated fiddle for a working version

神妖 2024-12-07 18:25:29

您已声明 var test_total 三次。您需要从每个循环内的两行开头删除“var”。一旦你删除它,它就会很好用......就像你所期望的那样。

var test_total = "EMPTY";

    // Check every hidden element with the classname "test_item".
    $(".test_item").each(function() {

        // Check if the hidden element is changed to 1 (link clicked).
        if ($(this).val() == "1") {
            // In case the variable we just made is still EMPTY, empty it and add the ID + Seperator
            if (test_total == "EMPTY") {
                test_total = $(this).attr("id") + "/SEPERATOR/";
            // In case the variable is not EMPTY anymore, use the previous entries and add a new ID+Seperator
            } else {
                test_total = test_total + $(this).attr("id") + "/SEPERATOR/";
            }
            alert("Variable test_total is now:\n" + test_total);
        }

    });

You have declared the var test_total three times. You need to remove "var " from the beginning of the two lines inside the each loop. Once you remove that, it works great... like you would expect.

var test_total = "EMPTY";

    // Check every hidden element with the classname "test_item".
    $(".test_item").each(function() {

        // Check if the hidden element is changed to 1 (link clicked).
        if ($(this).val() == "1") {
            // In case the variable we just made is still EMPTY, empty it and add the ID + Seperator
            if (test_total == "EMPTY") {
                test_total = $(this).attr("id") + "/SEPERATOR/";
            // In case the variable is not EMPTY anymore, use the previous entries and add a new ID+Seperator
            } else {
                test_total = test_total + $(this).attr("id") + "/SEPERATOR/";
            }
            alert("Variable test_total is now:\n" + test_total);
        }

    });
相守太难 2024-12-07 18:25:29

其他答案完全正确,您正在重新声明测试总负载。不过,一般来说,代码可以大大缩减。例如,

HTML

<input type="hidden" id="test1" class="test_item" value="0" />
<input type="hidden" id="test2" class="test_item" value="0" />
<input type="hidden" id="test3" class="test_item" value="0" />

<a href="#" class="HiddenFieldLink" data-hidden-field="test1">- Click me to check button 1</a><br />
<a href="#" class="HiddenFieldLink" data-hidden-field="test2">- Click me to check button 2</a><br />
<a href="#" class="HiddenFieldLink" data-hidden-field="test3">- Click me to check button 3</a><br />
<br /><br />
<a href="#" id="test_submit">Submit this</a>

我在链接上放置了一个类而不是 ID,删除了 javascript href 并为项目提供了 data- 属性来指示其匹配字段。

Javascript

$(document).ready(function() {
    // Text for button 1 clicked.
    $(".HiddenFieldLink").live('click', function(e) {
        var link = $(this),
            hiddenField = link.data('hiddenField');
        // BUTTON CLICKED
        $('#' + hiddenField ).val("1");
        // CHANGE TEXT
        link.text("Button clicked");

        e.preventDefault();
    });

    // The tricky party
    $("#test_submit").live('click', function() {
        var test_total = "EMPTY",
            entries = $.map($(".test_item"), function(item) {
                if(item.value === '1') {
                    return item.id;
                }
            });

        if(entries.length) {
            test_total = entries.join("/SEPERATOR/");
        }

        // Show me the output.
        alert("Variable test_total is now:\n" + test_total);
    });
});

现在我们只需要一个事件处理程序来处理所有修改隐藏字段的链接。另外 e.preventDefault();阻止链接尝试执行任何操作(比空白 JavaScript 更好)。

最后,我将提交语句切换为使用 jQuery $.map() 函数,这会返回从作为第二个参数提供的函数返回的项目数组。然后可以将其与您的分隔符连接起来。

这是 jsFiddle

The other answers are totally right, you're redeclaring the test total loads. The code in general could be shrunk way down though. E.g.,

HTML

<input type="hidden" id="test1" class="test_item" value="0" />
<input type="hidden" id="test2" class="test_item" value="0" />
<input type="hidden" id="test3" class="test_item" value="0" />

<a href="#" class="HiddenFieldLink" data-hidden-field="test1">- Click me to check button 1</a><br />
<a href="#" class="HiddenFieldLink" data-hidden-field="test2">- Click me to check button 2</a><br />
<a href="#" class="HiddenFieldLink" data-hidden-field="test3">- Click me to check button 3</a><br />
<br /><br />
<a href="#" id="test_submit">Submit this</a>

I've put a class on the links instead of an ID, removed the javascript href and given the items a data- attribute to indicate their matching field.

Javascript

$(document).ready(function() {
    // Text for button 1 clicked.
    $(".HiddenFieldLink").live('click', function(e) {
        var link = $(this),
            hiddenField = link.data('hiddenField');
        // BUTTON CLICKED
        $('#' + hiddenField ).val("1");
        // CHANGE TEXT
        link.text("Button clicked");

        e.preventDefault();
    });

    // The tricky party
    $("#test_submit").live('click', function() {
        var test_total = "EMPTY",
            entries = $.map($(".test_item"), function(item) {
                if(item.value === '1') {
                    return item.id;
                }
            });

        if(entries.length) {
            test_total = entries.join("/SEPERATOR/");
        }

        // Show me the output.
        alert("Variable test_total is now:\n" + test_total);
    });
});

Now we only need one event handler for all the links which modify the hidden fields. Additionally the e.preventDefault(); stops the link trying to do anything (nicer than blank javascript).

Finally I've switched the submit statement to use the jQuery $.map() function, this returns an array of items returned from the function provided as a second argument. This can then be joined with your seperator.

Here's the jsFiddle.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文