javascript函数使用jquery addClass()方法不添加类

时间:2012-12-13 14:10:32

标签: javascript jquery addclass

脚本工作,正确创建所有内容等,但jquery addClass方法不添加类。我是javascript函数中使用jquery方法的新手,我们很感激任何帮助,包括在不使用jquery的情况下添加相应类的替代方法。

function thumbnail(Img, Element, Modal, ModalTitle) {
"use strict";
/*jslint browser:true*/
/*global $, jQuery*/
//this function will append an anchor tag with the appropriate functionality, accepting inputs on the image filename, attaching element, and modal
//Img = full filename in format of foo.png
//Element = the ID of the element within which the thumbnail anchor will be placed
//Modal = the ID of the modal
//ModalTitle = Text used for title of the modal and title of the caption
var image, element, modal, loc, output, iUrl, modal_loc, modal_output, mtitle;
image = Img;
element = Element;
modal = Modal;
mtitle = ModalTitle;
iUrl = "/design-library/images/thumbs/" + image;
output = "<a href='#' data-reveal-id='" + modal + "'>";
output += "<img class='sample_img' src='" + iUrl + "' alt='" + mtitle + "' />";
output += "</a>";
output += "<p class='caption'>" + mtitle + "</p>";
modal_output = "<h1>" + mtitle + "</h1>";
modal_output += "<img src='" + iUrl + "' alt='" + image + "' /><a class='close-reveal-modal'>&#215;</a>";
//create the modal container
$(modal).addClass('reveal-modal');
modal_loc = document.getElementById(modal);
modal_loc.innerHTML = modal_output;
//the end of the script gets the element and adds the anchor tag that exists in output
$(element).addClass('samples');
loc = document.getElementById(element);
loc.innerHTML = output;
}

3 个答案:

答案 0 :(得分:5)

由于modalelement是ID,因此您应该更正您的选择器以将其用作1:

$('#' + modal).addClass('reveal-modal');
$('#' + element).addClass('samples');

旁注。使用jQuery找到DOM元素后,无需使用getElementById执行第二次搜索:

var modal_loc = $('#' + modal);
modal_loc.addClass('reveal-modal');
modal_loc.html(modal_output);

答案 1 :(得分:2)

如果modal是ID字符串,则需要执行以下操作:

$('#'+modal).addClass('reveal-modal');

答案 2 :(得分:1)

尝试更改:

$(element).addClass('samples');

$('#' + element).addClass('samples');