jQuery 将元素 ID 传递给 jquery 语句?

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

jQuery passing element ID into jquery statement?

jqueryvariablesconcatenation

提问by DA.

I'd like to pass the ID of an element into a function which then calls jQuery. However, I'm stumped as to how to actually take the ID variable and concatenate it with other text inside the jQuery statement. For example, this returns an error:

我想将元素的 ID 传递给一个函数,然后调用 jQuery。但是,我很难理解如何实际获取 ID 变量并将其与 jQuery 语句中的其他文本连接起来。例如,这将返回一个错误:

myFunction("#myObject");

function myFunction(IDofObject){

    $("'"+IDofObject+" img'").doSomething...

}

I'd like to do something with '#myObject img' but can't get that to work inside the statement.

我想用“#myObject img”做一些事情,但不能让它在语句中工作。

回答by tvanfosson

Don't wrap the parameter in quotes:

不要将参数用引号括起来:

function myFunction(IDofObject) {
    $( IDofObject + " img" ).doSomething();
}

Also, you may want to consider adding the hash character inside the function so you can pass it the actual id, not a selector.

此外,您可能需要考虑在函数中添加哈希字符,以便您可以将实际 id 传递给它,而不是选择器。

myFunction( $('.classSelector :first').attr('id') );

function myFunction(IDofObject) {
    $( "#" + IDofObject + " img" ).doSomething();
}

回答by inkedmn

myFunction("#myObject");

function myFunction(IDofObject){

    $(IDofObject+" img").doSomething...

}

Try that.

试试那个。

回答by karim79

I think you'd get better reuse if you passed an entire selector as a parameter, remembering that jQuery implicitly iterates over all matched elements. For a rudimentary example:

我认为如果你将整个选择器作为参数传递,你会得到更好的重用,记住 jQuery 隐式迭代所有匹配的元素。对于一个基本的例子:

function hideImageDescendants(selector){
    $(selector).find("img").hide();
}

回答by Mohsin Shoukat

When button is click then it get the button id which I later use to get it's field data, use + operator to dynamic change id

单击按钮时,它会获取我稍后用来获取其字段数据的按钮 id,使用 + 运算符来动态更改 id

$('.btnsave').click(function() 
  {
      btnvalue = $(this).val();
      //alert(btnvalue);
      adjust_value = $('#adjust_value'+btnvalue).val();
      ado = $('#ado'+btnvalue).val();
      amount =  $('#amount'+btnvalue).val();
      description = $('#description'+btnvalue).val();
      //alert(adjust_value+ado+amount+description);
      
  })

回答by DA.

Ugh. one of those '2 seconds after you ask you figure out...' questions:

啊。“在你问出问题后的 2 秒内……”问题之一:

function myFunction(IDofObject){

    $(IDofObject+" img").doSomething...

}

回答by CodeJoust

Just do this--

就这样做——

myfunction('obj')
function myfunction(obj){
$('#'+obj+' img').show();
}

Or, even

甚至

myfunction($('#2 img a'));

myfunction(jqobj){
jqobj.show();
}