jQuery动态ID [英] jquery dynamic id

查看:90
本文介绍了jQuery动态ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此类代码访问商品

i use such code to access item

function f(id){

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

对吗?还有其他方法吗?

is it correct? is any other methods?

推荐答案

如果要返回具有指定id的元素的值,请选择yes,因为这似乎是函数的逻辑用途:

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:

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

函数应假定存在具有指定id的元素,然后它会向您返回该元素的值.这对于input字段以及textarea应该都适用.但是,如果它是其他任何元素,则可能要使用html()text()而不是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 input fields as well as textarea. If however, it is any other element, you might want to use html() or text() instead of val() eg:

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

这篇关于jQuery动态ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆