简体   繁体   English

如何使用jQuery获取页面加载元素的ID

[英]How to get the id of an element ON PAGE LOAD using jQuery

I simply know how to get the id of a clicked element it's like this: 我只是知道如何获取被点击元素的ID,就像这样:

$("button").click(function(){
console.log($(this).attr("id"));
}

but what can I do for getting the id on web page load? 但是如何获取网页加载ID? Look at this.. 看这个..

$("button").ready(function(){
console.log($(this).attr("id"));
}

it returns the whole document object and this one .. 它返回整个文档对象和一个..

$("button").load(function(){
console.log($(this).attr("id"));
}

simply does nothing. 根本什么也没做。

I want to dynamically change the styles of all buttons on load. 我想动态更改加载时所有按钮的样式。

The main project is more complicated, and I don't want to use js core to do it, I want the simplicity of jQuery selector, but equivalent js approaches are appreciated. 主项目更加复杂,我不想使用js核心来实现它,我想要jQuery选择器的简单性,但是可以使用等效的js方法。

i want to dynamically change the styles of all buttons on load. 我想动态更改加载时所有按钮的样式。

If that is the case you can simply apply the css to the button selector on load, without needing to get the id of each button. 如果是这种情况,您只需在加载时将css应用于button选择器,而无需获取每个按钮的id

$(function() {
    $("button").css("background-color", "#C00");
});

Or better yet, put the css styling into a class and just apply a class to all the buttons: 或者更好的方法是,将css样式放入类中,然后将类应用于所有按钮:

$(function() {
    $("button").addClass("red-bg");
});

If you did want to get the id of each button on load, you'd need to use an array to cater for the fact there may be more than one button: 如果确实要获取加载时每个按钮的id ,则需要使用一个数组来满足可能存在多个按钮的事实:

var buttonIds = $("button").map(function() {
    return this.id;
}).get();

However, this is a rather pointless method as you can just use each() to iterate over the button selector anyway to get access to each indiviual button element. 但是,这是一个毫无意义的方法,因为您可以只使用each()遍历button选择器来访问每个单独的按钮元素。

you can get the all button elements in jquery and then loop on each button element to change their style -: 您可以在jquery中获取所有按钮元素,然后在每个按钮元素上循环以更改其样式-:

$(function()
{
    var allButtons = $('button');
    $.each(allButtons,function(index,element)
    {
        $(element).css('width','100px');
    });
});

I think you're looking for this: 我认为您正在寻找这个:

        $(document).ready(function () {
            $(":button").each(function () {
                console.log($(this).attr("id"));
            })
        });

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

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