我无法查看H1标签,然后使用基于所述H1内容的图像填充空div。我的代码如下:
// DECLARE MEASURMENT STEP IMAGES
var CornerRight = "../product_images/uploaded_images/onecutcornerrightstep2.gif";
var CornerLeft = "../product_images/uploaded_images/onecutcornerleftstep2.gif";
var CutCorners = "../product_images/uploaded_images/cutcornerssquareorrectanglestep2.gif";
var Rounded = "../product_images/uploaded_images/roundedsquareorrectanglestep2.gif";
var TwoCut = "../product_images/uploaded_images/2cutcornersstep2.gif";
var Round = "../product_images/uploaded_images/roundstep2.gif";
var Octagon = "../product_images/uploaded_images/octogonstep2.gif";
var SquareOrRectangle = "../product_images/uploaded_images/squareorrectanglestep2.gif";
// PLACE IMAGES
if ($( ".product h1:contains('Corner Right')" )) {
$( ".measurement-image" ).append("<img src=\"" + CornerRight + "\" />");
} else if ($( ".product h1:contains('Corner Left')" )) {
$( ".measurement-image" ).append("<img src=\"" + CornerLeft + "\" />");
} else if ($( ".product h1:contains('Cut Corners')" )) {
$( ".measurement-image" ).append("<img src=\"" + CutCorners + "\" />");
} else if ($( ".product h1:contains('Rounded')" )) {
$( ".measurement-image" ).append("<img src=\"" + Rounded + "\" />");
} else if ($( ".product h1:contains('Two Cut')" )) {
$( ".measurement-image" ).append("<img src=\"" + TwoCut + "\" />");
} else if ($( ".product h1:contains('Octagon')" )) {
$( ".measurement-image" ).append("<img src=\"" + Octagon + "\" />");
} else if ($( ".product h1:contains('Square or Rectangle')" )) {
$( ".measurement-image" ).append("<img src=\"" + SquareOrRectangle + "\" />");
} else {
$( ".measurement-image" ).append("<img src=\"" + Round + "\" />");
}
每次运行时,无论H1的实际内容如何,第一个条件(Corner Right)都会返回true。
答案 0 :(得分:1)
正如@linstantnoodles所说,你只是在检查一个数组是否存在,而不是该数组中是否包含元素
另外,为什么不减少变量的数量并使一个对象包含所有检查?这是我提议的改造:
var measureSteps = [
cornerRight: {
name: "Corner Right",
src: "../product_images/uploaded_images/onecutcornerrightstep2.gif";
},
cornerLeft: {
name: "Corner Left",
src: "../product_images/uploaded_images/onecutcornerleftstep2.gif";
},
cornerRight: {
name: "Cut Corners",
src: "../product_images/uploaded_images/cutcornerssquareorrectanglestep2.gif";
},
/* ETC, ETC */
];
//Iterate through each value in the "measureSteps" object, checking if it is contained in h1
var headerText = $('.product h1').text(); //Only do a jQuery matching search once
$.each(measureSteps, function(i, v) {
if ( headerText.indexOf(v.name) > -1 ) {
$( ".measurement-image" ).append("<img src='" + v.src + "' />");
return false; //Stop iterating - we've successfully found the right text!
}
});
答案 1 :(得分:0)
您需要检查结果(数组)的长度。 JavaScript中的所有对象都是真实的。
例如:
if ([]) {
console.log("Hello");
}
// Prints "Hello"