从字符串获取div id值并进行操作 [英] Getting div id values from a string and manipulating it
问题描述
我该如何实施?我有一个用逗号分隔的div名称的变量.在AJAX请求之后,我必须隐藏从字符串中解析的所有div.那么,如何解析字符串以获取单独的div名称并将其隐藏?
How do I implement this? I have a variable with comma separated div names. After an AJAX request I have to hide all the divs parsed from the string. So how do I parse the string to get individual div name and hide it?
jQuery代码
var dragExternal = 'div1a,div1b,div2a,div2b';
$.ajax({
type: 'POST',
url: "index.html",
data: dragExternal,
processData: false,
success: function(data) {
alert("Success");
//Start of code to hide all the div's parsed from the string
$('#div1a').slideUp(90);
},
error: function(data) {
alert("Cannot Reach Server");
}
});
HTML代码
<div id="div1a">Item 1</div>
<div id="div1b">Item 2</div>
<div id="div2a">Item 3</div>
<div id="div2b">Item 4</div>
<div id="div3a">Item 5</div>
<div id="div3b">Item 6</div>
推荐答案
首先,您必须从dragExternal
获取所有ID.通过使用string.split(',')
来实现.
Firstly, you'd have to get all the IDs from dragExternal
. Do this by using string.split(',')
.
然后,您可以使用 jQuery.each 方法来遍历每个项目.>
Then you can use the jQuery.each method to go through each of the items.
var dragExternal = 'div1a,div1b,div2a,div2b';
$.each(dragExternal.split(','), function(i,item){
$("#" + item).hide();
});
示例: http://jsfiddle.net/jonathon/UMCrC/
尽管您甚至都不需要$ .each(虽然很高兴知道用法)-因为它们都是字符串:
Although you don't even need $.each (it's nice to know the usage though) - since they're all just strings:
var dragExternal = 'div1a,div1b,div2a,div2b',
items = dragExternal.split(',')
for(var i=0;i<items.length;i++){
$("#" + item[i]).hide();
};
您可以使用 id选择器通过在div名称前添加
You use the id selector to get each div by prefixing the div name with #
.
这篇关于从字符串获取div id值并进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!