簡體   English   中英

使用jquery addClass()方法的javascript函數不會添加類

[英]javascript function using jquery addClass() method does not add class

該腳本可以正常工作,可以正確創建所有內容,等等,但是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;
}

由於modalelement是ID,因此您應該更正選擇器以將其用作ID:

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

邊注。 使用jQuery找到DOM元素后,就無需使用getElementById執行第二次搜索:

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

如果modal是一個ID字符串,則需要執行以下操作:

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

嘗試更改:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM