Javascript jquery动态id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2895528/
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-23 02:22:06  来源:igfitidea点击:

jquery dynamic id

javascriptjquery

提问by kusanagi

i use such code to access item

我使用这样的代码来访问项目

function f(id){

$("#"+id).val(); // with analogy $("#id item")
}

is it correct? is any other methods?

这是正确的吗?还有其他方法吗?

回答by Sarfraz

If you want to return the value of an element with specified id, then yes as that is what seems to be logical purpose of your function:

如果您想返回具有指定 id 的元素的值,那么是的,因为这似乎是您的函数的逻辑目的:

function f(id){
  return $("#" + id).val();
}

The functions should assume that an element with specified id exists and then it returns you the value of that element. This should work for inputfields as well as textarea. If however, it is any other element, you might want to use html()or text()instead of val()eg:

这些函数应该假设存在具有指定 id 的元素,然后它会返回该元素的值。这应该适用于input字段以及textarea. 但是,如果它是任何其他元素,您可能想要使用html()text()代替val()例如:

function f(id){
  return $("#" + id).html();
  // return $("#" + id).text();
}

回答by Sean Kinsey

You could use PureDom

你可以使用 PureDom

function f(id){
   return document.getElementById(id).value;
}

Take that, jQuery!

拿那个,jQuery!

回答by microspino

From the jQuery API website:

来自 jQuery API 网站:

.val() Returns: String, Array

Description: Get the current value of the first element in the set of matched elements.

.val() 返回:字符串、数组

描述:获取匹配元素集合中第一个元素的当前值。

What It's not clear to me when you say

当你说的时候我不清楚

// with analogy $("#id item")

// 类比 $("#id item")

is if you want to have ONLY one child item of the one that is identifiedby #id or if you need the item that is identified by item#id.

是如果您只想拥有由#id 标识的项目的一个子项目,或者如果您需要由项目#id 标识的项目。

Your code is perfect if you are passing a string like "hello" inside your code and you want to get the DOM element with ID of #hello.

如果您在代码中传递像“ hello”这样的字符串并且想要获取 ID 为#hello的 DOM 元素,那么您的代码是完美的。

回答by Darin Dimitrov

Yes this is perfectly valid way to access the element having its id.

是的,这是访问具有其 id 的元素的完全有效的方式。