gpt4 book ai didi

javascript - 如何使用 jQuery 确定 DOM 元素的类型

转载 作者:行者123 更新时间:2023-12-02 18:22:28 26 4
gpt4 key购买 nike

我正在使用以下代码:

$('#product-create-step-2 input, #product-create-step-2 img').each(function() {             
// I should check here if element is input or img
// If element is input I should get $(this).val()
// If element is img I should get $(this).attr('src')
var type = $(this).attr("type");
if ((type == "checkbox" || type == "radio") && $(this).is(":checked")) {
inputValues[$(this).attr('id')] = $(this).val();
} else if (type != "button" || type != "submit") {
inputValues[$(this).attr('id')] = $(this).val();
}
});

如何检查我拥有哪种类型的 DOM 元素以获得正确的值?

我知道 jQuery 中有一个函数 :is(),但示例取自 SO:Finding the type of an element using jQuery is for one element and not for a list。

更新

这是我正在处理的代码:

var inputValues = [];
$('#product-create-step-2 input, #product-create-step-2 img').each(function(i, e) {
e = $(e);

if (e.is("input")) {
var type = $(this).attr("type");
if ((type == "checkbox" || type == "radio") && $(this).is(":checked")) {
inputValues[$(this).attr('id')] = $(this).val();
}
else if (type != "button" || type != "submit") {
inputValues[$(this).attr('id')] = $(this).val();
}
} else if (e.is("img")) {
inputValues[$(this).attr('id')] = $(this).attr()
}
});

但我收到此错误:

TypeError: e is undefined

为什么?

解决方案

最后,在测试了乔通过的所有解决方案后,这是结果(请随意提出任何建议)

$('#product-create-step-2 input, #product-create-step-2 img').each(function(i, e) {
var that = $(this);
var thatis = this.src || this.value;
inputValues[that.attr('id')] = thatis;
});

最佳答案

你可以尝试使用这个:

$('#product-create-step-2 input, #product-create-step-2 img').each(function() {        
var myVar = this.value || this.src;
});

注意:src 某些输入类型的有效属性,因此仅当您的输入均未设置该属性时这才有效。否则,这将完美地工作,因为 img 没有 value 属性,并且(大多数)输入没有 src

如果您的某些输入确实具有src属性,那么请查看Logan的答案。

这里正在工作:http://jsfiddle.net/9Kerf/1/

关于javascript - 如何使用 jQuery 确定 DOM 元素的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18702774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com