将 Div id 分配给变量 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9410517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:46:13  来源:igfitidea点击:

Assign Div id to variable jQuery

jquery

提问by Rahul

I am trying to assign div id to a variable in jQuery .

我正在尝试将 div id 分配给 jQuery 中的变量。

 var tbdiv = null;
    tbdiv= $('#mydiv');

But this is throwing error in my jQuery file as ' Invalid argument '.

但这在我的 jQuery 文件中抛出错误为“无效参数”。

I am trying to do the following code which is in javascript

我正在尝试执行以下 javascript 代码

var tbdiv =document.getElementById('mydiv');

回答by Sarfraz

You can use attr:

您可以使用attr

var tbdiv= $('#mydiv').attr('id');
// or: var tbdiv = $('#mydiv')[0].id; 

I would though simply do:

我虽然简单地做:

var tbdiv= '#mydiv'

to assign id.

分配id。



If you MEANTassigning element itself, this should work fine:

如果您分配元素本身,这应该可以正常工作:

var tbdiv = $('#mydiv');

Or with vanilla JS:

或者使用香草 JS:

var tbdiv = document.getElementById('mydiv');

回答by Greg B

If you are trying to select the divthen the following should work:

如果您尝试选择,div那么以下应该有效:

var tbdiv = $('#mydiv');

If you wan't to select the ID of the div, then why use jQuery, you already know the ID because you are using it to make the call to jQuery.

如果您不想选择 的 ID div,那么为什么要使用 jQuery,您已经知道 ID,因为您正在使用它来调用 jQuery。

Is jQuery loaded? Are you getting any other errors in the console?

jQuery 加载了吗?您是否在控制台中收到任何其他错误?

回答by T.J. Crowder

I can't see any reason that the code

我看不到代码的任何原因

var tbdiv = null;
tbdiv= $('#mydiv');

...would throw any kind of exception provided that

...会抛出任何类型的异常,前提是

  1. jQuery is loaded, and

  2. jQuery has the $symbol. Some other libraries use it, and so jQuery offers noConflictmode. If you've included code somewhere calling noConflict, $will no longer refer to jQueryand you'd have to use this instead:

    tbdiv = jQuery('#mydiv');
    
  1. jQuery 已加载,并且

  2. jQuery 有$符号。其他一些库使用它,因此 jQuery 提供了noConflict模式。如果您在某处包含了调用noConflict, 的代码,$将不再引用jQuery,您必须改用它:

    tbdiv = jQuery('#mydiv');
    


Note that your JavaScript example is wrong. It would be getElementById('mydiv')(without the #, since the argument to getElementByIdis an ID, not a selector).

请注意,您的 JavaScript 示例是错误的。它将是getElementById('mydiv')(没有#,因为参数 togetElementById是一个 ID,而不是一个选择器)。