Javascript 引用错误:Can';与swift一起使用时找不到变量:jQuery?
我在swift中使用javascript。我正在为此使用JavaScriptCore。我已经创建了一个锯齿状的JS文件&正在加载它。下面是JS文件的代码Javascript 引用错误:Can';与swift一起使用时找不到变量:jQuery?,javascript,jquery,ios,swift,javascriptcore,Javascript,Jquery,Ios,Swift,Javascriptcore,我在swift中使用javascript。我正在为此使用JavaScriptCore。我已经创建了一个锯齿状的JS文件&正在加载它。下面是JS文件的代码 function setOldCities(appCities) { var city_array = appCities.split(','); for (var i = 0; i < city_array.length; i++) { // Trim the excess whitespace.
function setOldCities(appCities) {
var city_array = appCities.split(',');
for (var i = 0; i < city_array.length; i++) {
// Trim the excess whitespace.
city_array[i] = city_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
jQuery('.map-pin').each(function() {
if (($(this).attr('city') == city_array[i])) {
$(this).addClass("active");
try {
webkit.messageHandlers.callFromActivity.postMessage();
} catch(err) {
console.log('The native context does not exist yet');
}
}
});
}
}
从下面的代码中,我将JS文件加载到swift上下文中
func initializeJS() {
self.jsContext = JSContext()
// Add an exception handler.
self.jsContext.exceptionHandler = { context, exception in
if let exc = exception {
print("JS Exception:", exc.toString())
}
}
// Specify the path to the jssource.js file.
if let jsSourcePath = Bundle.main.path(forResource: "maps", ofType: "js", inDirectory: "map/js") {
do {
// Load its contents to a String variable.
let jsSourceContents = try String(contentsOfFile: jsSourcePath)
// Add the Javascript code that currently exists in the jsSourceContents to the Javascript Runtime through the jsContext object.
self.jsContext.evaluateScript(jsSourceContents)
}
catch {
print("error is \(error.localizedDescription)")
}
}
let consoleLogObject = unsafeBitCast(self.consoleLog, to: AnyObject.self)
self.jsContext.setObject(consoleLogObject, forKeyedSubscript: "consoleLog" as (NSCopying & NSObjectProtocol))
_ = self.jsContext.evaluateScript("consoleLog")
}
映射pin类位于单独的html文件中。我已经在html文件中包含了maps.js我无法从上面的代码中分辨出来——你在任何地方导入了jQuery吗?我在index.htmlc中导入了jQuery,你能用jQuery完成代码片段吗?我添加了所有的代码,有人能帮我解决这个问题吗
func initializeJS() {
self.jsContext = JSContext()
// Add an exception handler.
self.jsContext.exceptionHandler = { context, exception in
if let exc = exception {
print("JS Exception:", exc.toString())
}
}
// Specify the path to the jssource.js file.
if let jsSourcePath = Bundle.main.path(forResource: "maps", ofType: "js", inDirectory: "map/js") {
do {
// Load its contents to a String variable.
let jsSourceContents = try String(contentsOfFile: jsSourcePath)
// Add the Javascript code that currently exists in the jsSourceContents to the Javascript Runtime through the jsContext object.
self.jsContext.evaluateScript(jsSourceContents)
}
catch {
print("error is \(error.localizedDescription)")
}
}
let consoleLogObject = unsafeBitCast(self.consoleLog, to: AnyObject.self)
self.jsContext.setObject(consoleLogObject, forKeyedSubscript: "consoleLog" as (NSCopying & NSObjectProtocol))
_ = self.jsContext.evaluateScript("consoleLog")
}