nested-function 相关问题


如何防止点击时嵌套 React 组件中的事件冒泡?

这是一个基本组件。 和 都有 onClick 函数。我只想触发 上的 onClick,而不是 。我怎样才能实现这个目标? 我玩过 这是一个基本组件。 <ul> 和 <li> 都有 onClick 函数。我只想触发 <li> 上的 onClick,而不是 <ul>。我怎样才能实现这个目标? 我尝试过 e.preventDefault()、e.stopPropagation(),但无济于事。 class List extends React.Component { constructor(props) { super(props); } handleClick() { // do something } render() { return ( <ul onClick={(e) => { console.log('parent'); this.handleClick(); }} > <li onClick={(e) => { console.log('child'); // prevent default? prevent propagation? this.handleClick(); }} > </li> </ul> ) } } // => parent // => child 我也有同样的问题。我发现 stopPropagation did 有效。我会将列表项拆分为一个单独的组件,如下所示: class List extends React.Component { handleClick = e => { // do something } render() { return ( <ul onClick={this.handleClick}> <ListItem onClick={this.handleClick}>Item</ListItem> </ul> ) } } class ListItem extends React.Component { handleClick = e => { e.stopPropagation(); // <------ Here is the magic this.props.onClick(); } render() { return ( <li onClick={this.handleClick}> {this.props.children} </li> ) } } React 使用事件委托和文档上的单个事件侦听器来处理冒泡事件,例如本例中的“单击”,这意味着不可能停止传播;当您在 React 中与真实事件交互时,真实事件已经传播。 React 的合成事件上的 stopPropagation 是可能的,因为 React 在内部处理合成事件的传播。 stopPropagation: function(e){ e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); } 关于 DOM 事件的顺序:CAPTURING vs BUBBLING 事件传播有两个阶段。这些被称为 “捕获” 和 “冒泡”。 | | / \ ---------------| |----------------- ---------------| |----------------- | element1 | | | | element1 | | | | -----------| |----------- | | -----------| |----------- | | |element2 \ / | | | |element2 | | | | | ------------------------- | | ------------------------- | | Event CAPTURING | | Event BUBBLING | ----------------------------------- ----------------------------------- 首先发生捕获阶段,然后是冒泡阶段。当您使用常规 DOM api 注册事件时,默认情况下事件将成为冒泡阶段的一部分,但这可以在事件创建时指定 // CAPTURING event button.addEventListener('click', handleClick, true) // BUBBLING events button.addEventListener('click', handleClick, false) button.addEventListener('click', handleClick) 在React中,冒泡事件也是你默认使用的。 // handleClick is a BUBBLING (synthetic) event <button onClick={handleClick}></button> // handleClick is a CAPTURING (synthetic) event <button onClickCapture={handleClick}></button> 让我们看一下handleClick回调(React): function handleClick(e) { // This will prevent any synthetic events from firing after this one e.stopPropagation() } function handleClick(e) { // This will set e.defaultPrevented to true // (for all synthetic events firing after this one) e.preventDefault() } 我在这里没有看到提到的替代方案 如果您在所有事件中调用 e.preventDefault(),您可以检查事件是否已被处理,并防止再次处理它: handleEvent(e) { if (e.defaultPrevented) return // Exits here if event has been handled e.preventDefault() // Perform whatever you need to here. } 关于合成事件和原生事件的区别,请参阅React文档:https://reactjs.org/docs/events.html 这是防止单击事件前进到下一个组件然后调用 yourFunction 的简单方法。 <Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button> 这不是 100% 理想,但如果在儿童中传递 props 太痛苦 -> 儿童时尚或为此目的创建 Context.Provider/Context.Consumer just),你正在处理另一个库,它有自己的处理程序,它在您的处理程序之前运行,您也可以尝试: function myHandler(e) { e.persist(); e.nativeEvent.stopImmediatePropagation(); e.stopPropagation(); } 据我了解,event.persist方法可以防止对象立即被扔回React的SyntheticEvent池中。因此,当你伸手去拿 React 中传递的 event 时,它实际上并不存在!这种情况发生在孙子中,因为 React 在内部处理事情的方式是首先检查父进程是否有 SyntheticEvent 处理程序(特别是如果父进程有回调)。 只要您不调用 persist 来创建大量内存以继续创建诸如 onMouseMove 之类的事件(并且您没有创建某种 Cookie Clicker 游戏,例如 Grandma's Cookies),就应该完全没问题! 另请注意:偶尔阅读他们的 GitHub,我们应该密切关注 React 的未来版本,因为他们可能最终会解决一些问题,因为他们似乎打算在编译器中折叠 React 代码/转译器。 如果您希望发生嵌套元素中的操作而不是父元素中的操作,那么,您可以从父元素的操作处理程序中检查目标的类型,然后基于该类型执行操作,即,如果目标是我们的嵌套元素,我们什么也不做。否则两个处理程序都会被调用。 // Handler of the parent element. Let's assume the nested element is a checkbox function handleSingleSelection(e) { if(e.target.type !== 'checkbox') { // We do not do anything from the // parent handler if the target is a checkbox ( our nested element) // Note that the target will always be the nested element dispatch(lineSelectionSingle({ line })) } } 我在 event.stopPropagation() 工作时遇到问题。如果您也这样做,请尝试将其移动到单击处理程序函数的顶部,这就是我需要做的来阻止事件冒泡。示例函数: toggleFilter(e) { e.stopPropagation(); // If moved to the end of the function, will not work let target = e.target; let i = 10; // Sanity breaker while(true) { if (--i === 0) { return; } if (target.classList.contains("filter")) { target.classList.toggle("active"); break; } target = target.parentNode; } } 您可以通过检查事件目标来避免事件冒泡。 例如,如果您将输入嵌套到 div 元素,其中有单击事件的处理程序,并且您不想处理它,则单击输入时,您可以将 event.target 传递到您的处理程序中,并检查处理程序应该是根据目标的属性执行。 例如,您可以检查 if (target.localName === "input") { return}。 所以,这是一种“避免”处理程序执行的方法 解决此问题的另一种方法可能是在子级上设置 onMouseEnter 和 onMouseLeave 事件。 (您的 < li > 标签) 每当鼠标悬停在子级上时,您都可以设置一个特定的状态,以阻止父级执行 onClick 函数内容。 比如: class List extends React.Component { constructor(props) { super(props) this.state.overLi = false } handleClick() { // do something } render() { return ( <ul onClick={(e) => { if (!this.state.overLi) { console.log("parent") this.handleClick() } }} > <li onClick={(e) => { console.log("child") // prevent default? prevent propagation? this.handleClick() }} onMouseEnter={() => this.setState({ overLi: true, }) } onMouseLeave={() => this.setState({ overLi: false, })} ></li> </ul> ) } } 我进行了很多搜索,但没有设法使用 e.stopPropagation() 为我的上下文实现任何解决方案 您可以验证点击的元素是否是预期的元素。 例如: class List extends React.Component { constructor(props) { super(props); } handleClick(e) { if(e.target.className==='class-name'){ // do something } } render() { return ( <ul {/* Replace this with handleClick */} onClick={(e) => { console.log('parent'); this.handleClick(); }} <li onClick={(e) => { console.log('child'); // prevent default? prevent propagation? this.handleClick(); }} </li> </ul> ) } } 执行此操作的新方法更加简单,并且会节省您一些时间!只需将事件传递到原始点击处理程序并调用 preventDefault();。 clickHandler(e){ e.preventDefault(); //Your functionality here }


如何在 Nested LazyColumn 中保持相同的幻灯片状态?

一个 LazyColumn 包含另一个 LazyColumn,第二个 LazyColumn 包含一个 HorizontalPager。每个寻呼机都包含一个列表。 如何解决这个问题,或者有人有其他更好的想法来实现......


释放函数体内std::function的内存

我需要将 std::function 作为 void 指针传递以异步执行,因此我在堆上创建了一个 std::function 。删除函数体内的 std::function 对象是否安全?请看...


azure function 应用程序环境的配置值

您正在开发一个Azure Function App。您使用 Azure Function App 主机不支持的语言开发代码。代码语言支持 HTTP 原语。 您必须部署...


javascript:如何中止 $.post()

我的post方法如下图: $(".buttons").click(function(){ var gettopic=$.post("topic.php", {id: topicId}, function(result){ // 处理返回结果的代码 }); }) 我尝试...


标签错误:渲染时出现 React JSX 样式标签错误

这是我的反应渲染函数 渲染:函数(){ 返回 ( 某事 .rr{ 红色; ...</desc> <question vote="94"> <p>这是我的反应渲染函数</p> <pre><code>render:function(){ return ( &lt;div&gt; &lt;p className=&#34;rr&#34;&gt;something&lt;/p&gt; &lt;style&gt; .rr{ color:red; } &lt;/style&gt; &lt;/div&gt; ) } </code></pre> <p>这给了我这个错误</p> <blockquote> <p>JSX:错误:解析错误:第 22 行:意外的标记:</p> </blockquote> <p>这里出了什么问题? 我可以将完整的普通 CSS 嵌入到 React 组件中吗?</p> </question> <answer tick="false" vote="130"> <p>使用 es6 模板字符串(允许换行)很容易做到。在你的渲染方法中:</p> <pre><code>const css = ` .my-element { background-color: #f00; } ` return ( &lt;div className=&#34;my-element&#34;&gt; &lt;style&gt;{css}&lt;/style&gt; some content &lt;/div&gt; ) </code></pre> <p>至于用例,我正在为一个 div 执行此操作,其中包含一些用于调试的复选框,我希望将其包含在一个文件中,以便稍后轻松删除。</p> </answer> <answer tick="true" vote="73"> <p>JSX 只是 javascript 的一个小扩展,它不是自己完整的模板语言。所以你会像在 javascript 中那样做:</p> <pre><code>return ( &lt;div&gt; &lt;p className=&#34;rr&#34;&gt;something&lt;/p&gt; &lt;style&gt;{&#34;\ .rr{\ color:red;\ }\ &#34;}&lt;/style&gt; &lt;/div&gt; ) </code></pre> <p><a href="http://jsfiddle.net/r6rqz068/" rel="noreferrer">http://jsfiddle.net/r6rqz068/</a></p> <p>但是根本没有充分的理由这样做。</p> </answer> <answer tick="false" vote="30"> <p>内联样式最好直接应用于组件 JSX 模板:</p> <pre><code>return ( &lt;div&gt; &lt;p style={{color: &#34;red&#34;}}&gt;something&lt;/p&gt; &lt;/div&gt; ); </code></pre> <p>演示:<a href="http://jsfiddle.net/chantastic/69z2wepo/329/" rel="noreferrer">http://jsfiddle.net/chantastic/69z2wepo/329/</a></p> <hr/> <p><strong>注意:JSX 不支持 style 属性的 HTML 语法</strong></p> <p>使用驼峰式属性名称声明属性,例如,</p> <pre><code>{ color: &#34;red&#34;, backgroundColor: &#34;white&#34; } </code></pre> <p>进一步阅读此处:<a href="http://facebook.github.io/react/tips/inline-styles.html" rel="noreferrer">http://facebook.github.io/react/tips/inline-styles.html</a></p> </answer> <answer tick="false" vote="20"> <p>这可以通过使用反引号“`”来完成,如下所示</p> <pre><code>return (&lt;div&gt; &lt;p className=&#34;rr&#34;&gt;something&lt;/p&gt; &lt;style&gt;{` .rr{ color:red; } `}&lt;/style&gt; &lt;/div&gt;) </code></pre> </answer> <answer tick="false" vote="10"> <p>“class”是 JavaScript 中的保留字。而是使用“className”。</p> <p>此外,您必须记住您使用的是 JSX,而不是 HTML。我不相信 jsx 会解析你的标签。更好的方法是使用您的样式创建一个对象,然后将其应用为样式(见下文)。</p> <pre><code>var styles = { color:&#34;red&#34;; } return ( &lt;div&gt; &lt;p style={styles}&gt;something&lt;/p&gt; &lt;/div&gt; ) </code></pre> </answer> <answer tick="false" vote="8"> <ol> <li>创建一个函数来处理插入样式标签。</li> <li>将所需的 CSS 添加到字符串变量中。</li> <li><p>将变量添加到 <pre><code>&lt;style&gt;</code></pre> 标记内返回的 JSX。</p> <pre><code>renderPaypalButtonStyle() { let styleCode = &#34;#braintree-paypal-button { margin: 0 auto; }&#34; return ( &lt;style&gt;{ styleCode }&lt;/style&gt; ) } </code></pre></li> </ol> </answer> <answer tick="false" vote="4"> <p>这就是我所做的:</p> <pre><code>render(){ var styleTagStringContent = &#34;.rr {&#34;+ &#34;color:red&#34;+ &#34;}&#34;; return ( &lt;style type=&#34;text/css&#34;&gt; {styleTagStringContent} &lt;/style&gt; ); </code></pre> </answer> <answer tick="false" vote="0"> <p>经过一番摸索和尝试,终于找到了解决方案。 关键是危险的SetInnerHTML。 代码如下:</p> <pre><code> &lt;script src=&#34;https://pie-meister.github.io/PieMeister-with Progress.min.js&#34;&gt;&lt;/script&gt; import React from &#39;react&#39; const style = ` &lt;pie-chart class=&#34;nested&#34; offset=&#34;top&#34;&gt; &lt;style&gt; path { stroke-linecap: round; stroke-width: 90; } [color1] { stroke: #BFBDB2; stroke-width: 50; } [color2] { stroke: #26BDD8; stroke-width: 60; } [color3] { stroke: #824BF1; } [part=&#34;path&#34;]:not([y]) { stroke: #BFBDB2; stroke-width: 60; opacity: 0.4; } &lt;/style&gt; &lt;slice color1 size=&#34;100%&#34; radius=&#34;200&#34;&gt;&lt;!--No label--&gt;&lt;/slice&gt; &lt;slice color1 size=&#34;88%&#34; radius=&#34;200&#34; y=&#34;65&#34;&gt;&lt;tspan&gt; $size&lt;/tspan&gt;&lt;/slice&gt; &lt;slice color2 size=&#34;100%&#34; radius=&#34;100&#34;&gt; &lt;/slice&gt; &lt;slice color2 size=&#34;40%&#34; radius=&#34;100&#34; y=&#34;165&#34;&gt;&lt;tspan&gt; $size&lt;/tspan&gt;&lt;/slice&gt; &lt;slice color3 size=&#34;100%&#34; radius=&#34;0&#34;&gt; &lt;/slice&gt; &lt;slice color3 size=&#34;10%&#34; radius=&#34;0&#34; y=&#34;265&#34;&gt;&lt;tspan&gt; $size&lt;/tspan&gt;&lt;/slice&gt; &lt;/pie-chart&gt;` export default function Styles() { return ( &lt;div dangerouslySetInnerHTML={{__html:style}}/&gt; ) } </code></pre> </answer> <answer tick="false" vote="-3"> <pre><code>import styled from &#39;styled-components; return ( &lt;div&gt; &lt;Test&gt;something&lt;/Test&gt; &lt;/div&gt; ) </code></pre> <p>下一步:</p> <pre><code>const Test = styled.p` color: red `; </code></pre> </answer> </body></html>


NodeJS 我当前的 Google Cloud 函数名称是什么?

我想使用当前Google Cloud Function的名称来驱动一些逻辑。如何确定我的 Google Cloud Function 名称是什么?


Azure Function Python V2 一个函数应用程序中的多个函数

我正在寻找有关在一个 Azure Function App 中为多个函数创建项目结构的指导。这是我之前读过的一篇文章 在一个 Azure Function App 中创建多个函数 有一个...


使用 Azure Function 运行时和 pytest 'ModuleNotFoundError:没有名为...的模块'时出现导入问题

我的项目结构如下所示: 回购/ |--模型/api |--function/function_app.py |--函数/工具.py |--函数/__init__.py |--测试/test_function_app.py ...


如何在Azure Function中获取连接字符串?

我在 Azure 云中有一个 Azure Function 和一个 PostreSQL DB。 我想从我的 Azure 函数访问连接字符串,我们将其称为 IT-PostgreSQL。 这是我的Azure功能: 命名空间


滚动时仅触发一次功能

我想在div滚动到视口时启动一个函数。我的问题是,每次我继续滚动时,该功能都会再次触发/启动。 HTML: <... 我想在 div 滚动到视口中时启动一个函数。我的问题是,每次我继续滚动时,该功能都会再次触发/启动。 HTML: <div class="box"></div> JS: $(document).ready(function() { function start() { alert("hello"); } $(window).scroll(function() { if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); start(); } else { $(".box").removeClass("green"); } }); }); 总结一下:当div滚动到视口中时,应该启动“start”函数。但触发一次后就不能再触发了。 小提琴 您可以设置一个标志,例如: var started = false; function start() { if(!started) { alert("hello"); } started = true; } 演示 $(document).ready(function() { var started = 0; function start() { if(started==0) { alert("Alert only once"); } started = 1; } $(window).scroll(function() { if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); start(); } else { $(".box").removeClass("green"); } }); }); *{margin:0;} .box { background: red; height: 200px; width: 100%; margin: 800px 0 800px 0; } .green { background: green; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <br /> <center> <br /> <h1>scroll down</h1> </center> <div class="box"></div> 有很多方法可以解决这个问题。您可以删除事件侦听器(因为您使用的是 jQuery,所以我将使用 on 和 off 方法): $(window).on('scroll', function() { if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); start(); } else { $(".box").removeClass("green"); } $(window).off('scroll'); }); 如果你希望窗口滚动方法在启动方法满足要求后停止..你可以这样做 $(document).ready(function() { var toggleScroll = false; function start() { alert("hello"); } $(window).one("scroll", checkToggleScroll); function checkToggleScroll(){ if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); toggleScroll = true; start(); } else { $(".box").removeClass("green"); } if(!toggleScroll){ $(window).one("scroll", checkToggleScroll); } } }); 当start()没有类$(".box)(在一定量的滚动后添加)时,只需运行"green"函数。 $(document).ready(function() { function start() { alert("hello"); } $(window).scroll(function() { if ($(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { if (!$(".box").hasClass("green")) { $(".box").addClass("green"); start(); } } else { $(".box").removeClass("green"); } }); }); .box { background: red; height: 200px; width: 100%; margin: 800px 0 800px 0; } .green { background: green; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="box"></div>


Azure Function App 无法启动 Docker 容器,原因是“Azure.RequestFailedException:指定的资源名称包含无效字符。”

我们有一个从 Docker 映像部署的 Azure Function 应用程序。 该函数正在运行 .NET 8.0,FUNCTIONS_EXTENSION_VERSION = ~4 且 FUNCTIONS_WORKER_RUNTIME = dotnet-isolated。 该应用程序包含...


了解 std::function 的开销并捕获同步 lambda

考虑以下简单示例: #包括 #包括 #包括 #包括 #包括 #包括...


新的 Azure Function App 处理已由另一个 Function App 处理过的 Blob

我有以下情况。我有一个在 Windows 应用服务计划上运行的功能。该函数处理 blob。该函数具有默认的 LogsAndContainerScan 触发器。现在过了一段时间我...


如何解决 Firebase Cloud Function 未在 SSR 的“/workspace/.next”中找到 Next.js 生产版本?

我之前问过这个问题,并且仍在为这个问题苦苦挣扎;谁能帮我解决这个问题: SSR Next.js 应用程序的 Firebase Cloud Function 未在...中找到生产版本


闪亮的server.R无法读取全局变量

./app 中的两个文件 ui.R 图书馆(闪亮) 一个<- 1 ui <- fluidPage( textOutput("test") ) server.R server <- function(input, output) { output$test <- renderText({ a ...


如果需要很长时间,如何在Javascript中设置稍后执行的函数?

函数等待() { 让 a = Date.now() while (Date.now() - 一个 < 3000) { //loop } console.log('waiting ends...') } function start(){ console.log('starts...') wait() }


购物车变换功能

我想使用购物车转换创建扩展包。首先,我复制了“input.grqphql”和“index.ts”,如下所示:[PR (https://github.com/Shopify/function-examples/pull/276)] 之后,我...


希腊字母被替换为???一旦我使用 PHPWord 将 docx 转换为 pdf?

我做了以下简单的 laravel artisan 命令: Artisan::command('测试:pdf',function(){ \PhpOffice\PhpWord\Settings::setPdfRendererName(\PhpOffice\PhpWord\Settings::PDF_RENDERER_DOMPDF); ...


发送 csv 时“(400) 输入错误。某些域无效”

H。我需要通过ajax发送csv文件。我写了这段代码 $('#send-csv').click(function(){ var CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]').getAttribute("c...


Javascript 私有方法:函数表达式与函数声明[重复]

在 JavaScript 中创建(某种)私有方法的常见方法是: 类=函数(arg0,arg1){ var private_member = 0; var privateMethod = function () { 返回


导入 NodeJS 模块中的所有导出

我希望能够访问模块的所有导出,而不必说模块。出口前。 假设我有一个模块: // mymod.js module.exports.foo = function() { 控制台.log(...


概括 Julia 中 nlsolve 函数的输入

这个问题已经在另一个平台上问过了,但我还没有得到答案。 https://discourse.julialang.org/t/generalizing-the-inputs-of-the-nlsolve-function-in-julia/ 延长一段时间后...


具有多个值的JS var

有件事我无法理解: 我有一个打开同一页面的功能,但具有不同的内容,具体取决于菜单中单击的按钮: 有件事我无法理解: 我有一个打开同一页面的功能<div id="page">但具有不同的内容,具体取决于菜单中单击的按钮: <nav> <button onclick="openPage(1)">PAGE 1</button> <button onclick="openPage(2)">PAGE 2</button> <button onclick="openPage(3)">PAGE 3</button> </nav> 然后是函数: function openPage(p){ var move=0; // define a var for USER action if(p==1){ document.getElementById('page').innerHTML = text_1; // content preloaded } else if(p==2){ document.getElementById('page').innerHTML = text_2; } else if(p==3){ document.getElementById('page').innerHTML = text_3; } // then on the top of the page (absolute + z-index) I add a HTML object: document.getElementById('page').innerHTML += '<aside id="pictures">content</aside>'; // what I'm now trying to do is to remove this object once USER move its mouse on it document.getElementById('pictures').addEventListener("mousemove",function(event) { setTimeout(function(){ move+=1; // increase the val each second },1e3) console.log('move'+p+' = '+move) // control value if(move>100){ document.getElementById('pictures').style.display = "none"; // OK, it works move=0; // reinit the var } }); } 现在惊喜: 第 1 页的控制台 move1 = 0 move1 = 1 ... move1 = 99 move1 = 100 // 'pictures' disappears 第 2 页的控制台 move1 = 41 move2 = 0 ... move1 = 58 move1 = 17 ... move1 = 100 // 'pictures' disappears move2 = 59 第 3 页的控制台 move1 = 15 move2 = 88 move3 = 0 ... move1 = 37 move2 = 100 // 'pictures' disappears move3 = 12 ... 我的 var 'move' 同时获得 3 个值...这怎么可能? 您的问题的原因是您每次调用 openPage 函数时都会添加一个事件侦听器。这意味着,如果您单击多个按钮,每个按钮都会有自己的事件侦听器附加到 #pictures 元素。现在,当触发 mousemove 事件时,所有这些侦听器将同时执行,导致 move 变量每秒递增多次。 解决此问题的方法是在添加新事件侦听器之前先删除现有的事件侦听器。 let handler; // to hold the event listener function const pictureEl = document.getElementById('pictures'); function openPage(p){ // Remove existing event listener if (handler) { // <-- Check here pictureEl.removeEventListener("mousemove", handler); } handler = function(event) { // ...Rest } }; // Add new event listener pictureEl.addEventListener("mousemove", handler); // ...rest 找到了另一种(最简单的?)方法: var move=0; // placed out of functions function openPage(p){ .... (same as previous) getElementById('pictures').addEventListener("mousemove",outPicts); // change } // put mousemove event in another function: function outPicts(p){ setTimeout(function(){ move+=1; },1e3) console.log('move = '+move) if(move>100){ document.getElementById('pictures').style.display = "none"; // then remove event getElementById('pictures').removeEventListener("mousemove",outPicts); move=0; // reinit the var } } 按预期工作


如何在不重新加载页面的情况下发送带有文件的表单?

我尝试在ajax中发送表单而不重新加载页面,但我看到,文件上的链接不存在...... 我有下一个表格: 我尝试在ajax中发送表单而不重新加载页面,但我看到,文件上的链接不存在... 我有下一个表格: <form id="settings" method="POST" enctype="multipart/form-data"> ... <input type="file" id="logo" style="display:none;" name="logo" accept="image/png, image/jpeg, image/gif"> <button type="submit" id="send" class="btn btn-primary">save</button> </form> Ajax 脚本: $('#settings').submit(function(e){ e.preventDefault(); var form = $(this).serialize(); alert(form); // file is not attached... $.ajax({ url : '/settings', type : 'POST', crossDomain : false, data : form, contentType : 'multipart/form-data', dataType : 'json', progressData: false, cache : false, success : function(r){ alert (111); } }).fail(function(){ console.log('Error occured!'); }); }); 在服务器端,我收到错误: org.apache.tomcat.util.http.fileupload.FileUploadException:请求被拒绝,因为未找到多部分边界 我尝试不序列化表单,而是写了 data : form -> data : new FormData(this) 此选项会导致错误“非法调用”。如何在不重新加载页面的情况下发送带有文件的表单? 要使用 AJAX 发送带有文件的表单而不重新加载页面,您需要使用 FormData 来正确处理文件上传。 <form id="settings" method="POST" enctype="multipart/form-data"> <!-- Other form fields --> <input type="file" id="logo" name="logo" accept="image/png, image/jpeg, image/gif"> <button type="submit" id="send" class="btn btn-primary">Save</button> </form> $(document).ready(function() { $('#settings').submit(function(e){ e.preventDefault(); var formData = new FormData(this); $.ajax({ url: '/settings', type: 'POST', data: formData, contentType: false, processData: false, cache: false, success: function(response){ alert('Form submitted successfully!'); // Handle the response from the server }, error: function(){ console.log('Error occurred!'); } }); }); });


为什么将operator()作为std::function调用不起作用

考虑这个旨在收集字符串序列的小类: 班级问题_t期末 { 私人的: std::vector m_issues; 民众: constexpr void 运算符()(std::string&a...


单击嵌套跨度时禁用父按钮的单击效果

当我点击问号时,按钮父级有点击效果(这里是蓝色) 是否可以禁用它? 当我点击问号时,按钮父级有点击效果(这里是蓝色) 可以禁用它吗? <h:commandLink styleClass="btn btn-primary btn-lg" style="width: 100%;"> <span class="fa fa-trash"/> <span id="spanQuestion" class="fa fa-question" data-content="Help" data-html="true" data-popover="true"/> </h:commandLink> const span = $('#spanQuestion'); span.on("click", function(e) { e.stopPropagation(); }); 我试图停止对父项的点击,添加背景颜色。 我希望父按钮不会有点击效果。 ` 常量按钮 = $('#myButton'); const span = $('#spanQuestion'); span.on("click", function (e) { e.stopPropagation(); }); button.on("click", function (e) { // Your button click logic here }); `


Laravel POST 方法返回状态:405 不允许在 POST 方法上使用方法

请查找以下信息: NoteController.php 请查找以下信息: NoteController.php <?php namespace App\Http\Controllers; use App\Http\Requests\NoteRequest; use App\Models\Note; use Illuminate\Http\JsonResponse; class NoteController extends Controller { public function index():JsonResponse { $notes = Note::all(); return response()->json($notes, 200); } public function store(NoteRequest $request):JsonResponse { $note = Note::create( $request->all() ); return response()->json([ 'success' => true, 'data' => $note ], 201); } public function show($id):JsonResponse { $note = Note::find($id); return response()->json($note, 200); } public function update(NoteRequest $request, $id):JsonResponse { $note = Note::find($id); $note->update($request->all()); return response()->json([ 'success' => true, 'data' => $note, ], 200); } public function destroy($id):JsonResponse { Note::find($id)->delete(); return response()->json([ 'success' => true ], 200); } } NoteRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class NoteRequest extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'title', 'required|max:255|min:3', 'content', 'nullable|max:255|min:10', ]; } } Note.php(模型) <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Note extends Model { use HasFactory; protected $guarded = []; } api.php <?php use App\Http\Controllers\NoteController; use Illuminate\Support\Facades\Route; Route::prefix('v1')->group(function () { Route::resource('/note', NoteController::class); }); php artisan 路线:列表 GET|HEAD / ...................................................................................................................... POST _ignition/execute-solution ............... ignition.executeSolution › Spatie\LaravelIgnition › ExecuteSolutionController GET|HEAD _ignition/health-check ........................... ignition.healthCheck › Spatie\LaravelIgnition › HealthCheckController POST _ignition/update-config ........................ ignition.updateConfig › Spatie\LaravelIgnition › UpdateConfigController GET|HEAD api/v1/note .......................................................................... note.index › NoteController@index POST api/v1/note .......................................................................... note.store › NoteController@store GET|HEAD api/v1/note/create ................................................................. note.create › NoteController@create GET|HEAD api/v1/note/{note} ..................................................................... note.show › NoteController@show PUT|PATCH api/v1/note/{note} ................................................................. note.update › NoteController@update DELETE api/v1/note/{note} ............................................................... note.destroy › NoteController@destroy GET|HEAD api/v1/note/{note}/edit ................................................................ note.edit › NoteController@edit GET|HEAD sanctum/csrf-cookie .................................. sanctum.csrf-cookie › Laravel\Sanctum › CsrfCookieController@show 迅雷请求(同邮递员) JSON 请求 { "title": "Hello World", "content": "Lorem ipsum." } 尝试发出 JSON POST 请求并获取状态:405 方法不允许并且我正在使用 php artisan 服务,如果需要,我可以提供 GIT 项目。请告诉我。 您的验证规则看起来不正确。在您的 NoteRequest 类中,规则应该是一个关联数组,其中键是字段名称,值是验证规则。但是,在您的代码中,规则被定义为以逗号分隔的字符串列表。这可能会导致验证失败并返回 405 Method Not allowed 错误。 public function rules() { return [ 'title' => 'required|max:255|min:3', 'content' => 'nullable|max:255|min:10', ]; }


使用部分进行主动拆解/重新渲染不会重新渲染部分

这是小提琴(对警报感到抱歉)http://jsfiddle.net/PCcqJ/92/ var ractive = new Ractive({ 模板:'#templateOne', 部分:{ aPartial:'哦,看,partia... 这是小提琴(抱歉有警报)http://jsfiddle.net/PCcqJ/92/ var ractive = new Ractive({ template: '#templateOne', partials: { aPartial: '<div>Oh look, the partial is rendered!</div>' } }); function cb() { alert('but now we unrender'); ractive.once('complete', function() { alert('we rendered again, and now you can\'t see the partial content'); }); ractive.render('container'); } ractive.render('container'); ractive.once('complete', function() { alert('so we render the first time, and you can see the partial'); ractive.unrender().then(cb); }); 此处的部分不会重新渲染。为什么是这样?部分仍在部分对象中,并且它们尚未渲染,那么什么会阻止它们再次渲染? 这个小提琴会渲染、取消渲染,然后重新渲染,每次发生其中一种情况时都会向您发出警报。 我做了一个工作jsfiddle:https://jsfiddle.net/43gLqbku/1/ <div id='container'></div> <script id="templateOne" type="x-template"> {{>aPartial}} </script> var ractive = new Ractive({ el:"#container", template: '#templateOne', partials: { aPartial: '<div>Oh look, the partial is rendered!</div>' } }); function cb() { alert('but now we unrender'); ractive.once('complete', function() { alert('we rendered again, and now you can\'t see the partial content'); }); ractive.render('container'); } //ractive.partials.part = '<div>this is a partial</div>'; ractive.once('complete', function() { alert('so we render the first time, and you can see the partial'); ractive.unrender().then(cb); }); 在调用render之前需要调用ractive.once('completed') 你不需要 ractive.render("container");在活动代码下,因为它在第一次运行时自动呈现 在你的jsfiddle中你导入的ractive不起作用 你没有在 jsFiddle 活动代码中包含 el:"#container"


如何在 laravel 10 中设置子域

我正在尝试在我的项目中设置一个子域,但由于某种原因它不起作用。 路由::domain('{用户名}.' .env('APP_URL'))->group(function () { 返回“测试”; }); 它我...


替换R函数中变量名的多个实例并保存修改后的函数

上下文 考虑以下愚蠢的 MWE: 老有趣<- function(x) { VarA <- sum(x) VarA <- 2 * VarA VarX <- VarA %% 2 } I want to replace VarA with VarB and VarX VarY to get: new...


脚本无法在我的引导模式中工作

希望这不是一个愚蠢的问题,但我已经没有主意了...... 所以我有这个模式: 1.scala.html 希望这不是一个愚蠢的问题,但我已经没有主意了...... 所以我有这个模式: 1.scala.html <div class="feat" id="cor" data-toggle="tooltip" data-placement="bottom" title="add conference role"><div data-toggle="modal" data-target="#conf-role-menu-modal">Conference Role</div></div> <div class="modal fade" id="conf-role-menu-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body-conf-role-menu"> <script type="text/javascript"> $(function(){ $(".modal-body-conf-role-menu").load("@routes.Application.areaConferenceRole(id,idenv)"); }); </script> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> 使用模态主体中的脚本,我尝试加载此页面: 2.scala.html @(id:String, idenv:String) @Main("Add area") { <form action="@routes.Application.areaPostConferenceRole(id,idenv)" method="POST"> First Name: <input type="text" name="first_name" id="first" class="form-control"> Last Name : <input name="last_name" class="form-control"> <script type="text/javascript"> $( document ).ready(function() { // Handler for .ready() called. $( "#first" ).focus(function() { alert( "Handler for .focus() called." ); }); }); </script> </form> } 页面加载正常。我在我的模态中看到它...... 问题是我的页面 2.scala.html 中的脚本无法运行。我不明白为什么......如果我从我尝试在模态中加载的页面之外尝试它们,它们就会起作用...... $( document ).ready(function(){}); 永远不会在模态中到达,因为加载页面时已经触发了此事件(模态在之后加载...) 尝试直接插入脚本,如下所示: <script type="text/javascript"> $( "#first" ).focus(function() { alert( "Handler for .focus() called." ); }); </script> 当引导模式弹出时,shown.bs.modal事件将被触发。这是例子。 $('#myModal').on('shown.bs.modal', function () { $('#myInput').trigger('focus') }) Full documentation. https://getbootstrap.com/docs/4.0/components/modal/ 试试这个我已经准备好这个功能了 $('#myModal').on('shown.bs.modal', function () { // Your script here }); $(document).on('shown.bs.modal', '#myModal', function () { // Your script here });


没有匹配的函数可用于调用“std::thread::thread(<unresolved overloaded function type>)”

无效show_image(){ // 创建一个Mat来存储图像 马特凸轮图像; ERROR_CODE 错误; // 循环直到'e'被按下 字符键=''; while (key!= 'e') { // 抓取图像 错误= cam.grab(); ...


使用 VB 脚本将 JPEG 文件放入 Adobe Illustrator 中

我想获得有关如何使用 VB 脚本在 Adobe Illustrator 中放置 JPEG 文件的帮助。 我阅读了文档,但有很多 Place code @function 但我不确定哪一个合适。比如


使用 Java 从 Azure Function QueueTrigger 获取消息元数据

我正在使用 Micronaut 框架用 Java 编写一个 Azure 函数。 如果我使用 @QueueTrigger 注释一个字符串来接收消息正文,我的函数工作得很好。不过我也会


当布局更改或数据更改时,如何确保我的 ReactJS Bumbeishvili D3-Org-Chart 正确更新?

我已经在 CodeSandbox 上复制并简化了我的问题,可以在此处查看:https://codesandbox.io/p/sandbox/d3-org-chart-react-function-org-chart-gvfz4l?file=%2Fsrc %2F组件%2F数据...


我可以将几个未指定返回类型的 std::function 放入 C++ 的容器中吗?如果可以,该怎么做?

我想用C++编写一个通用的排序器。我有一些这样的代码。 模板 类排序器{ 民众: 模板 bool RegisterDimValueFetcher(const s...


如何在 Step Function 中包含 AWS Glue 爬网程序

这是我的要求: 我在 AWS Glue 中有一个爬虫和一个 pyspark 作业。我必须使用步骤功能设置工作流程。 问题: 如何将 Crawler 添加为第一个状态。参数是什么...


Laravel 动态扩展或使用 Traits

可以在运行时扩展或使用不同的类吗? 例子: 假设我们有一个名为 Player 的模型(我们的 A 模型) 可以在运行时扩展或使用不同的类吗? 示例: 假设我们有一个 model 称为 Player(我们的 A 模型) <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Player extends Model{ } 我们还有另外 2 个型号(B 和 C 型号) <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; protected $connection= 'db_b'; class PlayerInfoB extends Model{ function getName(){ return $this->name; } } 我们的C型号 <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; protected $connection= 'db_c'; class PlayerInfoC extends Model{ function getName(){ return $this->name_g; } } 模型A (Player)如何在运行时根据配置或其他数据扩展Model B or C 为什么我需要这个。 我有 2 个或更多不同的表,这些表的列有不同的名称,例如: Table 1 - name Table 2 - name_g Table 3 - name_full 所以我需要一个可以随时调用的包装器getName(),而无需检查现在使用的表。 $player = Player::get(); echo $player->getName(); 如果有不清楚的地方,请评论,我会更新我的问题。 更新基于madalin-ivascu答案可以这样完成吗? class Player extends Model{ protected $model; public function __construct(){ $this->setModel(); parent::__construct(); } protected function setModel(){ $this->model = $this->column_model_name } function getAttributeName(){ return $this->model->getName(); } } 如果不使用 eval 或 dirty hacks,就不可能在运行时编写一个类。您必须重新考虑您的类设计,因为您不太可能需要通过良好的设计来做到这一点。 您可以做的是使用方法 setTable 和 on: 在运行时更改模型实例上的表和数据库连接 Player::on('db_b')->setTable('player_info_b')->find($id); 另一种方法(首选)是定义模型 PlayerInfoC 和 PlayerInfoB 来扩展您的 Player 模型,然后根据您的情况在需要时实例化类 B 或 C。 在您的代码中,您的脚本必须具有您检查的状态,以便知道何时使用正确的模型? 既然如此,为什么不在 get name 中使用参数呢? class Player extends Model{ function getName($field){ return isset($this->{$field}) ? $this->{$field} : null; } } 如果你经常这样做,那么使用魔法方法: class Player extends Model{ function __get($key){ return isset($this->{$field}) ? $this->{$field} : null; } } ... echo $myModelInstance->{$field}; http://php.net/manual/en/language.oop5.overloading.php#object.get 在 Laravel 中,当你通过集合方法拉回数据时,它无论如何都会执行这个神奇的方法,因为所有属性都存储在称为属性的嵌套对象中,因此 __set() 和 __get() 看起来像这样: function __get($key){ return isset($this->attributes->{$key}) ? $this->attributes->{$key} : null; } function __set($key, $value){ return $this->attributes->{$key} = $value; } 建议后者带有属性子集,这样可以防止数据与返回的数据库列名称与模型中已使用的名称发生冲突。 这样,您只需在创建的每个模型中将一个属性名称作为保留名称进行管理,而不必担心您使用的数百个 var 名称会覆盖模型或模型扩展中的另一个属性名称。 使用该模型值来调用函数 $player = Player::get(); echo Player::getName($player->id,'PlayerInfoC'); 在 Player 模型中您只需调用 public static function getName($id,$class) return $class::where('player_id',$id)->getName();//each class will have the function } ps:您需要进行一些验证来测试该名称是否存在 另一种选择是在模型之间创建关系 您可以在模型中使用与以下相同的启动方法来执行此操作: protected static function booted() { if (<--your condition-- >) { $traitInitializers[static::class][] = 'boot' . ExampleTrait::class; $traitInitializers[static::class][] = 'boot' . Organizations::class; } }


使用 jquery javascript 搜索 jstree 节点

我正在使用 jstree 插件来构建我的树。我的网页中有一个搜索框,我需要用户能够在其中搜索 jstree 节点。 我正在使用 jstree 插件来构建我的树。我的网页中有一个搜索框,我需要用户能够在其中搜索 jstree 节点。 <fieldset id="search"> <input type="text" name="search_field" id="search_field" value="" /> <button id="search_tree">Search</button> </fieldset> 单击搜索时,jstree 节点应展开,如果找到,节点应突出显示。如果未找到,则应向用户显示错误,如“未找到”。我的代码用于展开下面的所有节点。有没有简单的方法来搜索jstree中的所有节点? <script type="text/javascript"> $(document).ready(function(){ $("#search_tree").click(function () { var value=document.getElementById("search_field").value; $("#tree").jstree("search",value); }); $("#tree").jstree({ "xml_data" : { "ajax" : { "url" : "jstree.xml" }, "xsl" : "nest" }, "themes" : { "theme" : "classic", "dots" : true, "icons" : true }, "search" : { "case_insensitive" : true, "ajax" : { "url" : "jstree.xml" } }, "plugins" : ["themes", "xml_data", "ui","types", "search"] }); }); </script> 我收到此错误: Instances[...] 为 null 或不是对象。这是一个 jstree 错误。有什么想法吗? 我已将这段代码添加到我的函数中: "search" : { "case_insensitive" : true, "ajax" : { "url" : "jstree.xml" } }, "plugins" : ["themes", "xml_data", "ui","types", "search"] 和 创建了此功能并与我的单击按钮相关联: function myFunction() { $(document).ready(function(){ var value=document.getElementById("search_field").value; $("#search_tree").click(function () { $("#tree").jstree("search",value) }); }); } 2023年,API逐年变化。使用版本v3.3.x, 这是我的工作代码: 创建jstree实例,配置如下: 当您搜索关键字时,请使用:


使用 Javascript 作为 http 触发语言的 Azure 函数 - 通过 VS Code 生成时缺少 function.json

我使用 Javascript 作为平台语言创建了 Azure Function。它工作和部署得很好。但是,它缺少 function.json。是否预计会生成,因为我看到其他帖子有...


使用 InertiaJs 和 Laravel 从数据库中删除用户

我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: 我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: <Link class="trash" @click="submit(result.ChildID)"> Move to Trash </Link> 注意: ChildID 是数据库中子记录的 id。 现在:当用户单击此链接时,将调用一个方法,如下所示。 methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete('destroy/ChildID'); } }, }, 路线代码 Route::delete('destroy/{childID}',[childrenController::class,'destroy']); 控制器代码 public function destroy(children $childID){ $childID->delete(); return redirect()->route('View_Child_Profile'); } 现在,当我点击删除按钮时,我收到以下错误: 试试这个。我认为你犯了错误“this.$inertia.delete('destroy/ChildID');” methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete(`destroy/${ChildID}`); // or this.$inertia.delete('destroy/'+ChildID); } }, }, 这是我处理删除过程的方式。 前视+惯性: import { Link } from '@inertiajs/inertia-vue3'; 在模板中: <Link method="delete" :href="route('admin.insta_feeds.destroy',id)">Delete</Link> 后端 Laravel: 路线: Route::resource('insta_feeds', InstaFeedsController::class); 控制器功能: public function destroy(InstaFeed $insta_feed) { if(isset($insta_feed->image_path)){ Storage::delete($insta_feed->image_path); } $insta_feed->delete(); return Redirect::route('admin.insta_feeds.index'); }


Python 中没有 Flask 服务器的 Azure 无服务器函数

在 AWS Lambda 中,无服务器函数是托管在某处的一小段代码。我可以卷曲一个网址来运行代码。在 python Function App v4 中,我似乎被迫使用服务器。有没有可能...


无法处理参数:builtin_function_or_method(<built-in function id>),它必须是列表、元组或字典类型

Python/MySQL(以及编程!)的全新体验。创建程序来存储食物的营养成分。然后每天创建一个消耗的食物表,该表将操纵食物表中的值。


C# HTTP 触发函数处理了一个请求。令牌请求失败

我收到以下记录:[错误] C# HTTP 触发器函数处理了请求。令牌请求失败。当我从门户运行 Azure Function 时。 当我从 Visual Studio 测试/运行应用程序时(在我的


php 使用函数更改函数外部变量的值

我试图在使用函数时更改函数外部声明的变量的值 我试图更改在使用函数时声明的变量的值 <?php $test = 1; function addtest() { $test = $test + 1; } addtest(); echo $test; ?> 但似乎不能。只有在函数中声明为参数的变量才有效。有这方面的技术吗?预先感谢 将函数内部的变量更改为全局变量 - function addtest() { global $test; $test = $test + 1; } 使用全局变量有很多注意事项 - 从长远来看,您的代码将更难维护,因为全局变量可能会对未来的计算产生不良影响,您可能不知道如何操纵变量。 如果重构代码并且函数消失,这将是有害的,因为 $test 的每个实例都与代码紧密耦合。 这里有一个轻微的改进,不需要 global - $test = 1; function addtest($variable) { $newValue = $variable + 1; return $newValue; } echo $test; // 1 $foo = addtest($test); echo $foo; // 2 现在您不必使用全局变量,并且可以根据自己的喜好操作 $test,同时将新值分配给另一个变量。 不确定这是否是一个人为的示例,但在这种情况下(与大多数情况一样),使用global将是极其糟糕的形式。为什么不直接返回结果并分配返回值呢? $test = 1; function increment($val) { return $val + 1; } $test = increment($test); echo $test; 这样,如果您需要增加除 $test 之外的 任何其他 变量,您就已经完成了。 如果您需要更改多个值并返回它们,您可以返回一个数组并使用 PHP 的 list 轻松提取内容: function incrementMany($val1, $val2) { return array( $val1 + 1, $val2 + 1); } $test1 = 1; $test2 = 2; list($test1, $test2) = incrementMany($test1, $test2); echo $test1 . ', ' . $test2; 您还可以使用 func_get_args 接受动态数量的参数并返回动态数量的结果。 使用 global 关键字。 <?php $test = 1; function addtest() { global $test; $test = $test + 1; } addtest(); echo $test; // 2 ?> 也许你可以试试这个。 <?php function addTest(&$val){ # Add this & and val will update var who call in from outside $val += 1 ; } $test = 1; addTest($test); echo $test; // 2 $anyVar = 5; addTest($anyVar); echo $anyVar; // 6


Azure 函数(dotnet-isolated)无法启动,并出现 Grpc.Core.RpcException:StatusCode="Unavailable" - Mac M1

我最近得到了一台Mac M1,并且正在设置我的机器以进行Azure Function(dotnet-isolated)开发。 我按照下面的文档进行操作,该文档在我的 Windows 10 计算机上运行得非常好。


使用 Future Function 时图像未显示在容器中,但当我使用图像小部件时会显示图像

代码应该在容器中显示图片,但它没有显示任何内容!除了文字之外。我使用 Image.asser() ,它可以工作并在容器中显示图像,但是当我...


Pinia 对象在 Vue 中的 foreach 后失去反应性

我有这个嵌套的foreach BalanceItemList.vue ... 我有这个嵌套的 foreach BalanceItemList.vue <template> <div v-for="category in categoryItemsStore.balanceCategories" :key="category.id" class="mt-5"> <div class="border-black border-b bg-gray-200"> <span class="font-bold w-full">{{ category.name }}</span> </div> <div v-for="balanceItem in category.balance_items" :key="balanceItem.id"> {{ balanceItem.total = 500 }} <balance-item :balance-item="balanceItem" @update-balance-item="update"/> </div> <div> <balance-item-create :category="category.id" @create-balance-item="update"/> </div> <div v-if="categoryItemsStore.totals[category.id]" class="grid grid-cols-4-b t-2 ml-2"> <div :class="category.is_positive ? '': 'text-red-600' " class="col-start-4 border-t-2 border-black font-bold"> &euro;{{ categoryItemsStore.totals[category.id].total }} </div> </div> </div> </template> 我像这样检查了“balanceItem”的反应性 {{ balanceItem.total = 500 }} 它在商店中更新,但随后我有了我的平衡项目组件: BalanceItem.vue <script setup> import {reactive} from "vue"; import {useForm} from "@inertiajs/vue3"; import NumberInput from "@/Components/NumberInput.vue"; import {UseCategoryItemsStore} from "@/Stores/UseCategoryItemsStore.js"; const categoryItemStore = UseCategoryItemsStore() const props = defineProps({balanceItem: Object, errors: Object}) let item = reactive(props.balanceItem); const form = useForm(item); const emit = defineEmits(['update-balance-item']) const submit = () => { form.post(route('balance-item.update'), { preserveScroll: true, onSuccess: () => { props.balanceItem.total = 500 categoryItemStore.updateBalanceItemsTotals(form) emit('update-balance-item') } }) } </script> <template> <form @submit.prevent="submit"> <div class="grid grid-cols-4-b"> <span>{{ item.name }}</span> <NumberInput v-model="form.count" autofocus class=" mr-4 mt-1 block" type="number" @update:model-value="submit" /> <div :class="item.item_category.is_positive ? '' : 'text-red-600'" class="flex place-items-center"> <div class="pt-1 mr-1">&euro;</div> <NumberInput v-model="form.amount" :class="form.errors.amount ? 'border-red-600' : ''" autofocus class="mt-1 mr-4 w-5/6" type="text" @update:model-value="submit" /> </div> <div :class="item.item_category.is_positive ? '' : 'text-red-600'" class="flex place-items-center"> <div class="pt-1 mr-1 w-5/6">&euro;</div> <NumberInput v-model="form.total" autofocus class="mt-1 block" disabled style="max-width: 95%" type="text" /> </div> </div> </form> </template> 这是我测试反应性的商店。如果我增加输入的数字,则项目的计数保持不变 UseCategoryItemsStore.js import {defineStore} from "pinia"; import {ref} from "vue"; export const UseCategoryItemsStore = defineStore('UseCategoryItemsStore', () => { const balanceCategories = ref([]) const totals = ref([]) function getBalanceItems() { axios.get(route('balance-item.index')).then((response) => { balanceCategories.value = response.data // console.log(balanceCategories.value) }) } function getTotals() { axios.get(route('balance-item.totals')).then((response) => totals.value = response.data) } function getData() { getTotals() getBalanceItems() } function updateBalanceItemsTotals(selectedItem) { balanceCategories.value.forEach((category) => { category.balance_items.forEach((item) => { if (item.id === selectedItem.id) { // item.total = item.count * item.amount console.log(item) } }) }) } getTotals() getBalanceItems() return {balanceCategories, totals, getBalanceItems, getTotals, getData, updateBalanceItemsTotals} }) 在此测试中,我执行“props.balanceItem.total = 500”。但如果我检查商店,它不会更新。看来将“balanceItem”分配给一个道具会失去与我的 Pinia 商店的反应性。我可以使用“form.total = form.count * form.amount”手动更新我的表单,但这对我来说似乎很老套,我想使用 Pinia 商店的反应性。我考虑过根据“BalanceItem”获取 Pina 项目,但这似乎也很棘手。谁知道为什么失去反应性? 我有laravel 10.39、vue3.2.41和pinia 2.1.17惯性0.6.11。到目前为止我知道的所有最新版本。 我像这样更新我的表格和商店: <script setup> import {useForm} from "@inertiajs/vue3"; import NumberInput from "@/Components/NumberInput.vue"; import {UseCategoryItemsStore} from "@/Stores/UseCategoryItemsStore.js"; const categoryItemStore = UseCategoryItemsStore() const props = defineProps({balanceItem: Object, errors: Object}) let item = categoryItemStore.getItemById(props.balanceItem); let form = useForm(item); const emit = defineEmits(['update-balance-item']) const submit = () => { form.post(route('balance-item.update'), { preserveScroll: true, onSuccess: () => { item = categoryItemStore.updateItem(form) form = useForm(item) emit('update-balance-item') } }) } </script> 我将此功能添加到我的商店: import {defineStore} from "pinia"; import {ref} from "vue"; export const UseCategoryItemsStore = defineStore('UseCategoryItemsStore', () => { const balanceCategories = ref([]) const totals = ref([]) function getBalanceItems() { axios.get(route('balance-item.index')).then((response) => { balanceCategories.value = response.data // console.log(balanceCategories.value) }) } function getItemById(item) { let category = balanceCategories.value.find((category) => { return category.id === item.item_category_id }) return category.balance_items.find((item_from_store) => { return item_from_store.id === item.id }) } function updateItem(form) { const item = getItemById(form) item.count = form.count item.amount = form.amount item.total = item.count * item.amount return item } function getTotals() { axios.get(route('balance-item.totals')).then((response) => totals.value = response.data) } function getData() { getTotals() getBalanceItems() } getTotals() getBalanceItems() return {balanceCategories, totals, getBalanceItems, getTotals, getData, getItemById, updateItem} }) 假设如果帖子获得 200,我的表单值可用于更新商店和更新表单。这是我能想到的最好的


Javascript 函数 openFullscreen() ,如何让它在页面上的多个 iframe 上工作

在页面上我有一个 iframe,src 中有 *.pdf 文件。 <p>在页面上我有一个 iframe,src 中有 *.pdf 文件。</p> <pre><code>&lt;div class=&#34;node--view-mode-full&#34;&gt; &lt;p&gt;&lt;iframe allow=&#34;fullscreen&#34; allowfullscreen=&#34;&#34; frameborder=&#34;0&#34; height=&#34;980&#34; scrolling=&#34;no&#34; src=&#34;https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf&#34; width=&#34;660&#34;&gt;&lt;/iframe&gt;&lt;/p&gt; &lt;p&gt;&lt;iframe allow=&#34;fullscreen&#34; allowfullscreen=&#34;&#34; frameborder=&#34;0&#34; height=&#34;980&#34; scrolling=&#34;no&#34; src=&#34;https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf&#34; width=&#34;660&#34;&gt;&lt;/iframe&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>浏览器中内置的 pdf 查看器现在不支持 iframe 中的全屏模式。</p> <p>我找到了解决方案<a href="https://www.w3schools.com/howto/howto_js_fullscreen.asp" rel="nofollow noreferrer">https://www.w3schools.com/howto/howto_js_fullscreen.asp</a>,解决了问题 - 以全屏模式打开 iframe。在 w3schools 的示例中,打开 iframe 的按钮已存在于 HTML <a href="https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_fullscreen" rel="nofollow noreferrer">https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_fullscreen</a>.</p> <p>在我的解决方案中,我通过 javascript 添加按钮,因为带有 iframe 的页面已经存在,但没有此类按钮:</p> <pre><code>jQuery(document).ready(function($){ $(&#34;.node--view-mode-full iframe[src*=&#39;.pdf&#39;]&#34;).each(function (index) { $(this).addClass(&#39;fullscreenframe&#39;); $(this).attr(&#39;id&#39;, &#39;fullscreen-&#39;+index); $(&#39;&lt;button onclick=&#34;openFullscreen()&#34;&gt;Open in Fullscreen Mode&lt;/button&gt;&amp;nbsp;&lt;strong&gt;Tip:&lt;/strong&gt; Press the &#34;Esc&#34; key to exit full screen.&lt;br&gt;&#39;).insertBefore(this); }); }); </code></pre> <p>然后添加一个全屏打开 iframe 的功能(与 w3schools 相同):</p> <pre><code>function openFullscreen() { var elem = document.getElementsByClassName(&#34;fullscreenframe&#34;)[0]; if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { /* Safari */ elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { /* IE11 */ elem.msRequestFullscreen(); } }; </code></pre> <p>当页面上只有一个带有 *.pdf 的 iframe 时,Everysing 工作正常。但是,当我在页面上有两个或多个 iframe,并且单击任何 iframe 附近的“以全屏模式打开”任何按钮时,我总是在全屏模式下只看到第一个 *.pdf...</p> <p>我知道,这是因为我只得到 elem = document.getElementsByClassName("fullscreenframe")[0]; 中的第一个 iframe;</p> <p>我知道我需要使用类似的每个或类似的东西,但我无法解决它。在搜索关于页面上一个全屏元素的所有解决方案时,没有关于页面上多个元素的解决方案...谢谢。</p> </question> <answer tick="true" vote="0"> <p>也许是这样的:</p> <pre><code>jQuery(document).ready(function($){ $(&#34;.node--view-mode-full iframe[src*=&#39;.pdf&#39;]&#34;).each(function (index) { $(this).addClass(&#39;fullscreenframe&#39;); $(this).attr(&#39;id&#39;, &#39;fullscreen-&#39;+index); $(&#39;&lt;button onclick=&#34;openFullscreen(&#39; + index + &#39;)&#34;&gt;Open in Fullscreen Mode&lt;/button&gt;&amp;nbsp;&lt;strong&gt;Tip:&lt;/strong&gt; Press the &#34;Esc&#34; key to exit full screen.&lt;br&gt;&#39;).insertBefore(this); }); }); function openFullscreen(index) { var elem = document.getElementsByClassName(&#34;fullscreenframe&#34;)[index]; if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { /* Safari */ elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { /* IE11 */ elem.msRequestFullscreen(); } } </code></pre> </answer> <answer tick="false" vote="0"> <p>为什么不整合 jQuery?</p> <pre><code>const fullScreen = element =&gt; element.requestFullScreen(); // all modern browsers $(function(){ $(&#34;.node--view-mode-full iframe[src*=&#39;.pdf&#39;]&#34;).each(function (index) { $(this).addClass(&#39;fullscreenframe&#39;); $(this).attr(&#39;id&#39;, &#39;fullscreen-&#39;+index); $(&#39;&lt;button class=&#34;fullScreen&#34;&gt;Open in Fullscreen Mode&lt;/button&gt;&amp;nbsp;&lt;strong&gt;Tip:&lt;/strong&gt; Press the &#34;Esc&#34; key to exit full screen.&lt;br&gt;&#39;).insertBefore(this); }); $(&#34;.fullScreen&#34;).on(&#34;click&#34;, function() { const $iFrame = $(this).closest(&#39;p&#39;).find(&#39;iframe.fullscreenframe&#39;); if ($iFrame) fullScreen($iFrame.get(0)); // pass the DOM element }); }); </code></pre> </answer> </body></html>


© www.soinside.com 2019 - 2024. All rights reserved.