如何知道 JS 代码是在浏览器中执行还是在设计模式中执行
How to know if JS code is executing in browser or in design mode
相信intellisense可以解决很多时间和bug。假设我打了一个 ajax 电话,我知道我会得到一系列汽车。
$.ajax({
type: "POST",
url: "GetCars.aspx",
success: function (cars) {
for(var i = 0; i < cars.length; i++)
{
var car = cars[i];
if(document.designMode)
{
car = { type: "", model: 0, colors: new Array() };
}
// Intelissense wors great in here!
// car. "the moment I type the '.' I see type, model, and colors
}
}
});
我需要一些在 visual studio 编辑器中 return 为真而在浏览器中为假的东西。 if(document.designMode)
return 在 VS 和浏览器中为真,因此始终执行行 car = { type: "", model: 0, colors: new Array() };
。 我不希望 car = { type: "", model: 0, colors: new Array() };
行仅在 VS 的浏览器上执行,所以我得到了智能感知。我该怎么做?
解决方案
感谢@Shoms 我想到了:
var car = null;
if (window.navigator.userAgent.length === 212) {
car = { type: "", model: 0, colors: new Array() };
}
// Intellizense works great :)
请注意,您的 VS 可能需要不同的号码。对我来说,我必须尝试 > 500 然后 <250 , < 125 等等,直到我发现它的长度是 212。
您可以检查 userAgent 并根据它决定做什么。
您甚至可以在某些浏览器中设置自定义 userAgent,以备不时之需。
window.navigator.userAgent
因此,例如,您的情况可能是:
if(window.navigator.userAgent.indexOf('Mozilla') !== -1) {
// browser here
} else {
// VS here (or a non-Mozilla browser, but that's not relevant for development)
car = { type: "", model: 0, colors: new Array() };
}
相信intellisense可以解决很多时间和bug。假设我打了一个 ajax 电话,我知道我会得到一系列汽车。
$.ajax({
type: "POST",
url: "GetCars.aspx",
success: function (cars) {
for(var i = 0; i < cars.length; i++)
{
var car = cars[i];
if(document.designMode)
{
car = { type: "", model: 0, colors: new Array() };
}
// Intelissense wors great in here!
// car. "the moment I type the '.' I see type, model, and colors
}
}
});
我需要一些在 visual studio 编辑器中 return 为真而在浏览器中为假的东西。 if(document.designMode)
return 在 VS 和浏览器中为真,因此始终执行行 car = { type: "", model: 0, colors: new Array() };
。 我不希望 car = { type: "", model: 0, colors: new Array() };
行仅在 VS 的浏览器上执行,所以我得到了智能感知。我该怎么做?
解决方案
感谢@Shoms 我想到了:
var car = null;
if (window.navigator.userAgent.length === 212) {
car = { type: "", model: 0, colors: new Array() };
}
// Intellizense works great :)
请注意,您的 VS 可能需要不同的号码。对我来说,我必须尝试 > 500 然后 <250 , < 125 等等,直到我发现它的长度是 212。
您可以检查 userAgent 并根据它决定做什么。 您甚至可以在某些浏览器中设置自定义 userAgent,以备不时之需。
window.navigator.userAgent
因此,例如,您的情况可能是:
if(window.navigator.userAgent.indexOf('Mozilla') !== -1) {
// browser here
} else {
// VS here (or a non-Mozilla browser, but that's not relevant for development)
car = { type: "", model: 0, colors: new Array() };
}