简体   繁体   English

如何在JS中找到具有相似ID的元素?

[英]How could I find an element with similar ID in JS?

In my page I have labels that look like this: 在我的页面中,我的标签看起来像这样:

ContentPlaceHolder1_gvGroups_lblName_0

with corrosponding: 对应:

ContentPlaceHolder1_gvGroups_lblHidden_0

I can assert that any *lblName has a corrosponding *lblHidden. 我可以断言任何* lblName都有对应的* lblHidden。

Now, I have some js: 现在,我有一些js:

//use to make any label with 'edit' class editable
function makeLabelsEditable() {

    $(".edit").focusout(function () {
        setLabel(this);
    });

    $(".edit").click(function () {
        editLabel(this);
    });
}

//used to edit labels
function editLabel(source) {
    source.innerHTML = '<input type="text" maxlength="40" value="' + source.innerHTML + '"/>';
    $(source).unbind('click');
    source.children[0].focus()
}

//used to edit labels
function setLabel(source) {

    if (source.children[0].value != '') {
        $(source).click(function () {
            editLabel(this);
        });
        source.innerHTML = source.children[0].value;
    }

}

I can assert that anything marked with class edit will be valid. 我可以断言标记有class edit的所有内容都是有效的。

I need to modify this code like so: //used to edit labels 我需要像这样修改此代码://用于编辑标签

function setLabel(source) {

    if (source.children[0].value != '') {
        $(source).click(function () {
            editLabel(this);
        });
        source.innerHTML = source.children[0].value;
        var hidden = someHowGetHiddenFromSource(source);
        hidden.innerHTML = source.children[0].value;
    }

}

I'm sure this is possible, I just do not know how. 我敢肯定这是可能的,我只是不知道怎么做。

Essentially, it would be something like: 本质上,它将是这样的:

getElementByID(replace(source.id,'lblName','lblHidden'));

I just do not know what JS / JQ functions can do that. 我只是不知道什么JS / JQ函数可以做到这一点。

Thanks 谢谢

Essentially, it would be something like: getElementByID(replace(source.id,'lblName','lblHidden')); 从本质上讲,它将类似于: getElementByID(replace(source.id,'lblName','lblHidden'));

That's almost exactly it. 几乎就是这样。 It's: 它的:

var hidden = document.getElementById(source.id.replace('lblName', 'lblHidden'));

hidden will be the DOM element. hidden将是DOM元素。

Or using jQuery: 或使用jQuery:

var hidden = $("#" + source.id.replace('lblName', 'lblHidden'));

hidden will be a jQuery instance wrapping the element. hidden将是包装该元素的jQuery实例。

The id property of DOM elements is a string. DOM元素的id属性是一个字符串。 JavaScript strings have a replace function which accepts, in the simple case, the string to replace and the replacement string. JavaScript字符串具有replace功能,在简单情况下,该功能接受要替换的字符串和替换字符串。 (There's more to it than that, but that's all you need in this case.) (不仅限于此,在这种情况下,这就是您所需要的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM