简体   繁体   English

通过javascript和jquery获取.val元素的div元素

[英]Getting div elements by .val element with javascript and jquery

I have a script that generates div ids once a drop down box is clicked as shown below. 我有一个脚本,一旦点击下拉框,就会生成div ID,如下所示。 The div id is actually generated by the value of the item id. div id实际上是由item id的值生成的。 I can get the value but dont know how to add it. 我可以获得价值,但不知道如何添加它。 So basically it should be something like $('#itemsupdate2').load('index.php/sales #item ` (item id goes here... 所以基本上它应该像$('#itemsupdate2').load('index.php / sales #item`(item id在这里...

I just cant get it to work. 我无法让它发挥作用。 I can get the value by adding 我可以通过添加来获得价值

var item = $('input[name=item]').fieldValue(); var item = $('input [name = item]')。fieldValue();

this works and i can get the value in an alert box. 这工作,我可以在警告框中获取值。 I am not sure how to do a load with this value. 我不知道如何使用此值进行加载。 What I am trying to do is shown below. 我想要做的是如下所示。

$('#itemsupdate2').load('index.php/sales #item "+ item[0]+"').fadeIn('slow'); $('#itemsupdate2')。load('index.php / sales #item“+ item [0] +”')。fadeIn('slow');

<div class="itemsupdate">

<div id="item1">
sample text 1   
</div>

<div id="item8">
1guiness150.004 
</div>

<div id="item9">
1999999.009 
</div>

The ".val()" method has nothing to do with "id" values. “.val()”方法与“id”值无关。 What you're looking for is ".attr()": 你要找的是“.attr()”:

var theId = $(whatever).attr('id');

Now, you've got another problem. 现在,你还有另外一个问题。 The "id" values need to look like identifiers. “id”值需要看起来像标识符。 Thus, "9" won't work. 因此,“9”将不起作用。 You could use something like "_9" or whatever. 你可以使用像“_9”之类的东西。

$('select').bind('change', function() {
    var val = $(this).val();
    $('.itemsupdate').html('<div id="' + val +'">contents of the div</div>');
});

This will add the div to div.itemsupdate . 这会将div添加到div.itemsupdate

Then you can access it later like this : $('#' + $('select').val()); 然后您可以像这样访问它: $('#' + $('select').val());

.val() returns the value of the selected object. .val()返回所选对象的值。 This works great on textareas and inputs, but not on divs. 这适用于textareas和输入,但不适用于div。 Use .text() instead to get the text element, or use .html() to get the full html structure within the div. 使用.text()代替获取文本元素,或使用.html()获取div中的完整html结构。 In your example, you use ids to identificate your divs. 在您的示例中,您使用ID来标识您的div。 So why don't you use this id selector #? 那么你为什么不使用这个id选择器#?

$('#1').text(); // returns 'sample text 1'
$('#1').text('new text'); // will change the divs content with 'new text'
$('#1').text('text before '+$('#1').text()+' text after') // will insert 'text before' before the content and add 'text after' after the divs content: text before sample text 1 text after

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

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